Search code examples
c++lambdareferencevalue-categories

Should I make reference for a lambda?


Should I make reference for a lambda to avoid copying it?

Will this code make a copy of the lambda:

auto myLambda = []() {/* do stuff */ }

and if yes, should I write it like this:

auto &myLambda = []() {/* do stuff */ }

P.S. Please sorry for a possibly newbie question, googled, but didn't find answer.


Solution

  • You should use the first one because the second one is ill-formed according to the C++ standard.

    [expr.prim.lambda]/2:

    A lambda-expression is a prvalue whose result object is called the closure object. [ Note: A closure object behaves like a function object. — end note ]

    You cannot bind prvalues to lvalue references per [dcl.init.ref]/5. The fact that a particular compiler appears to accept it doesn't change anything. C++ is defined by the C++ standard.

    In fact, the first one is guaranteed not to introduce a copy since C++17 — initializing from prvalues is guaranteed to construct the value in place. In practice, every decent compiler does the copy elision optimization, so you can safely assume that no copy is made.