When a function takes an argument by value, it can usually modify it. However, this does not seem to be the case with lambdas. Why?
int main()
{
int x = 0;
auto lambda = [x] { x = 1; }; // error: assignment of read-only variable ‘x’
return 0;
}
Herb Sutter answered the question here as follow;
Consider this straw man example, where the programmer captures a local variable by value and tries to modify the captured value (which is a member variable of the lambda object):
int val = 0;
auto x = [=](item e) // look ma, [=] means explicit copy
{ use(e,++val); }; // error: count is const, need ‘mutable’
auto y = [val](item e) // darnit, I really can’t get more explicit
{ use(e,++val); }; // same error: count is const, need ‘mutable’
This feature appears to have been added out of a concern that the user might not realize he got a copy, and in particular that since lambdas are copyable he might be changing a different lambda’s copy.
Note: That is a proposal paper to change the feature.
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