Home >Backend Development >C++ >Why are C 11 Lambdas Capturing by Value Mutable by Default?
Mutability and Lambda Capture-by-Value in C 11
Lambda expressions in C 11 allow for the capture of external variables, either by reference or by value. However, when capturing by value, the mutable keyword is required by default. This has sparked questions regarding its necessity, especially given that traditional parameter passing to named functions does not require mutability.
The Rationale Behind Mutability
The key difference lies in the nature of lambdas as function objects. They are designed to produce consistent results with each invocation. If a lambda expression could alter its captured variables without declaring them as mutable, it would violate this principle. As a result, the compiler default assumes that capture-by-value variables should remain unmodified.
Mutable Declaration
The mutable keyword allows for the explicit modification of capture-by-value variables within a lambda expression. It acknowledges that the function object is intended to behave differently based on its current state. For example, the lambda below increments a counter each time it is executed:
int n = 0; [mutable](){ n++; }();
Implications and Alternatives
The requirement for mutability in capture-by-value ensures that lambdas maintain deterministic behavior. It also eliminates the need for capture-by-reference in many cases where the captured variable is not intended to be modified externally. However, it's worth noting that excessive use of mutable can hinder code clarity and introduces potential for side effects.
The above is the detailed content of Why are C 11 Lambdas Capturing by Value Mutable by Default?. For more information, please follow other related articles on the PHP Chinese website!