21

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;
}
dragonroot
  • 5,653
  • 3
  • 38
  • 63
  • 11
    By default, the closure's apply-operator is `const`. You can still modify the captured variables with `mutable`: `[x]() mutable { x = 1; }` See also: http://stackoverflow.com/q/5501959 – dyp Dec 31 '14 at 00:33

1 Answers1

12

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.

Alper
  • 12,860
  • 2
  • 31
  • 41