C ++ 11: Volatile lambda doesn't seem to modify a variable?
int i=2;
auto f=[=]()mutable{++i;};
f();
f();
std::cout<<i<<std::endl;
this prints 2.
int i=2;
auto f=[&](){++i;};
f();
f();
std::cout<<i<<std::endl;
this prints 4.
int i=2;
auto f=[=]()mutable{++i; std::cout << i << std::endl;};
f();
f();
std::cout<<i<<std::endl;
this prints 3 4 2.
=
copies the collected data to a lambda.
If copiesmutable
can be modified .
&
links the committed data to the lambda.
Changing links through links is legal.
[=]
is the same as, and [i]
, [&]
in this context, is the same as [&i]
(you can explicitly map the captures, or let them capture implicitly without listing any and using =
or &
).
source to share
[=]
means you are writing i
by value. Even a mutable lambda can change it, but it is just a copy inside the lambda, then any modification on it will have nothing to do with the original variable.
You may want capture-by-reference and then mutable
not needed anymore. eg.
auto f = [&i]() {++i;};
source to share