Chinese Yellow Pages | Classifieds | Knowledge | Tax | IME

Quota from a good article from

http://www.cprogramming.com/c++11/c++11-lambda-closures.html

It turns out that the way lambdas are implemented is by creating a small class; this class overloads the operator(), so that it acts just like a function.

A lambda function is an instance of this class; when the class is constructed, any variables in the surrounding enviroment are passed into the constructor of the lambda function class and saved as member variables.

If you make a lambda with an empty capture group, [], rather than creating the class, C++ will create a regular function.

Here’s the full list of options:

[] Capture nothing (or, a scorched earth strategy?)
[&] Capture any referenced variable by reference
[=] Capture any referenced variable by making a copy
[=, &foo] Capture any referenced variable by making a copy, but capture variable foo by reference
[bar] Capture bar by making a copy; don’t copy anything else
[this] Capture the this pointer of the enclosing class

 

Dangers and Benefits of Capture by Reference

When you capture by reference, the lambda function is capable of modifying the local variable outside the lambda function–it is, after all, a reference. But this also means that if you return a lamba function from a function, you shouldn’t use capture-by-reference because the reference will not be valid after the function returns

According to bjarne stroustrup: Using lambdas can be convenient and terse, but also obscure. For nontrivial actions (say, more than a simple expression), I prefer to name the operation so as to more clearly state its purpose and to make it available for use in several places in a program.

 

References

http://www.cprogramming.com/c++11/c++11-lambda-closures.html

Leave a Reply

Your email address will not be published. Required fields are marked *