Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are lambda arguments passed by value read-only in C++11?

Tags:

c++11

lambda

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;
}
like image 319
dragonroot Avatar asked Dec 31 '14 00:12

dragonroot


1 Answers

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.

like image 162
Alper Avatar answered Oct 03 '22 20:10

Alper