Delving into C 11 Lambda Capture-by-Value: Unraveling the Necessity of "Mutable" Keyword
In C 11, lambda expressions provide a powerful mechanism to create anonymous function objects. However, when capturing by value, the notorious "mutable" keyword often surfaces, leaving developers wondering about its purpose.
Consider the following snippet:
#include <iostream> int main() { int n; [&](){n = 10;}(); // OK [=]() mutable {n = 20;}(); // OK // [=](){n = 10;}(); // Error: a by-value capture cannot be modified in a non-mutable lambda std::cout << n << "\n"; // "10" }
Without the "mutable" keyword in the second lambda, the compiler reports an error. The question arises: why is this keyword necessary?
The Implicit Contract of Function Objects
Lambda expressions are instances of function objects. Function objects are expected to adhere to the basic principle of functional programming: referential transparency. This means that when called with the same set of arguments, the result should always be the same.
When capturing by value, the lambda expression creates a local copy of the variable. However, this poses a potential problem. If the lambda modifies the copy, the original variable's value may change, violating the principle of referential transparency.
Enforcing Referentiality with "Mutable"
The "mutable" keyword breaks this implicit contract. By specifying it, the compiler allows the lambda expression to modify the captured value. This grants the developer explicit control over the mutability and side effects of the lambda.
Without "mutable," the compiler enforces referential transparency by preventing the lambda from modifying any captured values. This ensures that the lambda always returns the same result for a given set of arguments, making it a true function object.
Striking a Balance
The "mutable" keyword provides a necessary balance between referential transparency and the flexibility to modify captured values. It allows the developer to choose whether or not the lambda can affect the outside world.
Therefore, the "mutable" keyword in capture-by-value lambdas is not merely a convention, but a crucial safeguard that preserves the fundamental nature of function objects: reliable and predictable behavior.
The above is the detailed content of When is the `mutable` Keyword Necessary in C 11 Lambda Capture-by-Value?. For more information, please follow other related articles on the PHP Chinese website!