C++11 introduced lambdas, allowing the definition of inline functionality, which can be used as a parameter or a local object.Lambdas change the way the C++ standard library is used.
Syntax of Lambdas
A lambda is a definition of functionality that can be defined inside statements and expressions. Thus, you can use a lambda as an inline function.
The minimal lambda function has no parameters and simply does something. For example:
1 | [] { |
You can call it directly: …mutable_opt throwSpec_opt->retType_opt{…}
1 | [] { |
or pass it to objects to get called:
1 | auto l = [] { |
lambda introducer,capture to access nonstatic outside objects inside the lambda.static objects such as std::cout can be used
|
…mutable_opt throwSpec_opt->retType_opt
|
all of them are optional,bug if one of them occurs,the parentheses for the parameters are mandatory
mutable关系到[…]中的数据是否可以被改写(objects are passed by value,but inside the function object defined by the lambda, you have write access to the passed value.),可以取用外部变量
(…)函数的参数
retType,without any specific definition of the return type, it is deduced from the return value.
you can specify a capture to access data of outer scope that is not passed as an argument:
[=]means that the outer scope is passed to the lambda by value.
[&]means that the outer scope is passed to the lambda by reference.
1 | Ex: |
1 | //The type of a lambda is an anouymous function object (or functor) |
Here is what compiler generates for lambda’s:
1 | 1、 |