Search code examples
c++lambdareferencereturnreturn-type

I'm Returning a Reference From a Lambda, why is a Copy Happening?


It's been brought to my attention by the answer to this question that lambdas I thought were returning by reference are copying. If we define this for example:

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

None of this code calls the copy constructor:

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

But this code calls the copy constructor on return:

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

Live Example

I don't get it. Why is it returning by copy? Or more generally I guess I should ask: "How does a lambda decide how to return?"


Solution

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

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