Home >Backend Development >C++ >Why is the `mutable` Keyword Necessary for Capture-by-Value in C 11 Lambdas?
In C 11, lambdas captured by value are functionally immutable, meaning they cannot modify the captured values by default. To amend this behavior, the "mutable" keyword is employed to allow modifications within the lambda's scope.
Consider the following example:
int main() { int n; [&]() { n = 10; }(); // OK, captures by reference [=]() mutable { n = 20; }(); // OK, captures by value with "mutable" // [=](){n = 10;}(); // Error, cannot modify by-value capture without "mutable" std::cout << n << "\n"; // Prints "10" }
The question arises: Why is the "mutable" keyword necessary for capture-by-value?
Traditionally, parameters passed to named functions are implicitly mutable, allowing for modifications within the function. However, lambdas provide both capture-by-reference and capture-by-value mechanisms, which introduce distinct behavior.
By default, capture-by-value creates a copy of the external variable, and the lambda may only operate on this temporary value. Without "mutable," any attempt to modify the captured value will result in a compiler error, as it violates the principle of immutability for function objects.
Therefore, the "mutable" keyword is introduced to explicitly allow modifications within a lambda that captures by value. It signals to the compiler that the captured copy can be treated as mutable, thus returning to a more traditional function-like behavior.
In summary, the "mutable" keyword is required for capture-by-value in C 11 lambdas because it ensures that the function object's output remains consistent with its inputs, while allowing for modifications to the captured copy within the lambda's scope.
The above is the detailed content of Why is the `mutable` Keyword Necessary for Capture-by-Value in C 11 Lambdas?. For more information, please follow other related articles on the PHP Chinese website!