I am returning a link from lambda, why is copying going on?

This was brought to my attention by the answer to this question , which the lambdas, which I thought were returning by reference, copy. If we define this, for example:

struct A { A() = default; A(const A&) { cout << "copy\n"; } }; 

None of these codes call the copy constructor:

 A a; const A* pa = &a; const A& ra = *pa; 

But this code calls the returned copy constructor:

 [](const A* pa){ return *pa; }(pa); 

Live example

I do not understand. Why is he returning a copy? Or, as a rule, I should ask: "How does lambda decide how to return?"

-one
source share
1 answer

The return type is lambda auto ( [expr.prim.lambda]/4 ), so a copy will be made if you do not explicitly specify it with the return type:

 [](const A* pa) -> const auto& { return *pa; }(pa); 
+2
source

Source: https://habr.com/ru/post/1013797/


All Articles