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.