The need for a keyword mutablein lambdas is a 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";
Conclusion:
Before lambda: x = 10
Inside lambda: x = 11
After lambda: x = 10
As we can see, the variable xremains unchanged after lambda, so there are no side effects.
However, if we βforgetβ the variable keyword , we get an error.
Being an argument passing the default value in C ++, it makes no sense for me to use a mutable keyword.
Can someone write (even in pseudo-code) a class generated by the compiler instead of lambda?
thank
source
share