C++ Lambda Expression Quick Reference¶
Syntax¶
Basic syntax:
[captures] (params) { body }
where
- captures: A comma-separated list of things that the body can refer to.
- Things that can be captures include:
- The capture-default, which can be one of the followings:
&
: All variables used in the body are "captured by reference"=
: All variables used in the body are "captured by copy"
- The
this
pointer - The individual variables
- The capture-default, which can be one of the followings:
- The capture-default, if used, must be the first entry in the list.
- The captures can be an empty list
- Things that can be captures include:
- params: The parameter list of the lambda expression
- body: The function body
Some examples:
// Create a lambda function that adds 2 to the input int value
auto f1 = [](int a1) { return a1 + 2; };
int f1_out = f1(10); // return 12
// Create a lambda function that captures the local variable x by copy
int x = 5;
auto f2 = [x](int a1) { return a1 + x; };
x = 6;
int f2_out = f2(10); // return 15 because x was 5 when f2 was created.
// Create a lambda function that captures the local variable x by reference
auto f3 = [&x](int a1) { return a1 + x; };
x = 7;
int f3_out = f3(10); // return 17 because x was 7 when f3 was called.