When lambda expression's captures by reference( [&]
) marking mutable
or not it still changing the value. But capturing by value needs mutable
to change the object.
int main(){
int x = 10;
auto ByValue = [x](){ --x; }; // error: decrement of read-only variable 'x'
auto ByRef = [&x](){ --x; }; //No Error
auto ByValM = [x]()mutable{ --x; }; // No error
auto ByRefM = [&x]()mutable{ --x; }; // No error
}
Why [&x](){ --x; };
is able to change the variable x
? Is it that capturing by reference marks the lambda expression mutable
implicitly?