0

In the following code, assigning to an std function results in more copy constructor calls than assigning to an auto variable. ( actually initializing, not assigning ;) )

I get that a value captured local must be copied.

I get that each time i assign it to a new std::function an extra copy will be needed.

But why is there a difference between initializing an auto var and and a function var?

#include <iostream>
#include <functional>
using namespace std;
struct A { A()=default; A(const A&) {cout << "CC\n";} };
int main()
{
    A a1;
    //auto f = [a1] (){}; // just 1 CC
    //[a1] (){}; // just 1 CC
    function<void()> f=[a1] (){}; // 2 CC 

    return 0;
}
Gonen I
  • 5,576
  • 1
  • 29
  • 60
  • [Capturing lambda in std::function results in extra copies](https://stackoverflow.com/questions/69352888/capturing-lambda-in-stdfunction-results-in-extra-copies) – Jason Mar 02 '23 at 13:33
  • My very uneducated guess is that it's because a Lambda is a particular non-nameable type while std::function is a templated wrapper around that type, so you need to copy the Lambda type into the function type? Doesn't entirely explain why it doesn't just move, but I guess that's at least part of it. – kouta-kun Mar 02 '23 at 13:34
  • All lambdas are really handled as objects of compiler-generated classes, where the captures are basically members of that class. By creating a copy of the lambda object, all the captures (members of the lambda object) will also be copied. – Some programmer dude Mar 02 '23 at 13:34
  • There is a proposal to change this: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p0792r10.html – doctorlove Mar 02 '23 at 13:36
  • See also [Creating std::function with lambda causes superfluous copying of the lambda object - why?](https://stackoverflow.com/questions/23515058/creating-stdfunction-with-lambda-causes-superfluous-copying-of-the-lambda-obje) – Jason Mar 02 '23 at 13:37
  • @JasonLiam While I appreciate the links, they do not answer the correct question. They explain why a copy constructor is invoked on captures, which I established as known to me in the question description. Other answers refer to move, which is not a part of this question. Yet another has an argument in the lambda which causes the extra copy. Just because 2 questions show the same symptoms or have similar names, does not mean the explanation is the same. – Gonen I Mar 02 '23 at 13:44
  • Nitpick: there are no assigments in that code, only initializations. – molbdnilo Mar 02 '23 at 13:46
  • 3
    There's conceptually two copies in the `auto` case too, but the copying part of the initialization gets elided. Since the second is a conversion, there is no opportunity to avoid the second copy. – molbdnilo Mar 02 '23 at 13:54

0 Answers0