The need of the keyword mutable
in lambdas, is source of great confusion.
Consider the code:
int x = 10;
function<void()> lambda = [=]() mutable {x++; cout << "Inside lambda: x = " << x << "\n";};
cout << "Before lambda: x = " << x << "\n";
lambda();
cout << "After lambda: x = " << x << "\n\n";
Output:
Before lambda: x = 10
Inside lambda: x = 11
After lambda: x = 10
As we can see, the variable x
stays unchanged after the lambda, so there are no side effects.
However, if we "forget" the keyword mutable, we get an error.
Being the argument passing by value the default in C++, it doesn't make sense for me the need of the mutable keyword.
Can someone write (even in pseudo code) the class generated by the compiler, in place of the lambda?
Thank you