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.
Long lambda expressions consisting of several statements may reduce the readability of your code. In such a case, extracting those statements in a method and referencing it may be a better choice.
The mutable keyword is used so that the body of the lambda expression can modify its copies of the external variables x and y , which the lambda expression captures by value. Because the lambda expression captures the original variables x and y by value, their values remain 1 after the lambda executes.
You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name.
The method references can only be used to replace a single method of the lambda expression. A code is more clear and short if one uses a lambda expression rather than using an anonymous class and one can use method reference rather than using a single function lambda expression to achieve the same.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With