Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 571
Nurbol Alpysbayev Avatar asked Aug 29 '19 08:08

Nurbol Alpysbayev


People also ask

Which is better lambda or method reference?

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.

Does lambda capture reference by value?

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.

What are we using lambdas and method reference for?

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.

How do you use method reference instead of lambda?

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.


1 Answers

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.

like image 156
L. F. Avatar answered Oct 09 '22 07:10

L. F.