Capture by reference

suggest change

If you precede a local variable’s name with an &, then the variable will be captured by reference. Conceptually, this means that the lambda’s closure type will have a reference variable, initialized as a reference to the corresponding variable from outside of the lambda’s scope. Any use of the variable in the lambda body will refer to the original variable:

// Declare variable 'a'
int a = 0;

// Declare a lambda which captures 'a' by reference
auto set = [&a]() {
    a = 1;
};

set();
assert(a == 1);

The keyword mutable is not needed, because a itself is not const.

Of course, capturing by reference means that the lambda must not escape the scope of the variables it captures. So you could call functions that take a function, but you must not call a function that will store the lambda beyond the scope of your references. And you must not return the lambda.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Lambdas:
* Capture by reference

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype