I have a program as below:
int main()
{
int val = 4;
auto add = [val](int a)->int{
val += 2;
return a+val;
};
cout << add(3) << endl;
cout << val << endl;
return 0;
}
There's a compiling error in Xcode: Cannot assign to a variable captured by copy in a non-mutable lambda.
My question is: if we choose to use the copy (using "=" or value name), can't this value be assigned a new value or changed?
The
operator ()
of a lambda is implicitlyconst
unless the lambda is declaredmutable
- and you can't modify the data members in aconst
member function. This happens regardless of the type of the capture.Inside a lambda, captured variables are immutable by default. That doesn't depend on the captured variables or the way they were captured in any way. Rather, the function call operator of the closure type is declared
const
:Therefore, if you want to make the captured variables modifiable inside the body, just change the lambda to
so the
const
-specifier is removed.Just capture it by reference, it will work !!