http://coliru.stacked-crooked.com/a/29520ad225ced72d
#include <iostream>
struct S
{
void f()
{
//auto f0 = [] { ++i; }; // error: 'this' was not captured for this lambda function
auto f1 = [this] { ++i; };
auto f2 = [&] { ++i; };
auto f3 = [=] { ++i; };
f1();
f2();
f3();
}
int i = 10;
};
int main()
{
S s;
std::cout << "Before " << s.i << std::endl;
s.f();
std::cout << "After " << s.i << std::endl;
}
Before 10
After 13
Question: Why does [=]
enable modification of member variables in a lambda?
Question> Why [=] enables modification of member variables in lambda?
Because (see cpp reference) [=]
"captures all automatic variables odr-used in the body of the lambda by value and current object by reference if exists"
So [=]
capture the current object by reference and can modify i
(that is a member of the current object).
If you write in equivalent way, this behavior will be more clear:
auto f3 = [=] { ++(this->i); };
You not catch i
but this
, it will be constant but thing that its points to will be editable as in any other pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With