Why are lambda arguments passed by value read-only

2020-04-02 08:20发布

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;
}

标签: c++11 lambda
1条回答
2楼-- · 2020-04-02 08:47

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.

查看更多
登录 后发表回答