A mutable lambda in C++ is an anonymous function object that allows the modification of variables captured by value. By default, the compiler-generated function call operator (Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
operator()) of a lambda expression is const-qualified, making by-value captures read-only. Appending the mutable keyword removes this const qualification, enabling the lambda’s body to mutate its internal state (the copied variables) without affecting the original variables in the enclosing scope.
Syntax
Themutable specifier is placed after the parameter list and before the trailing return type (if specified) or the function body.
mutable specifier is used, the parameter list () is strictly mandatory, even if the lambda accepts no arguments. As of C++23 (via proposal P1102R2), the empty parameter list () is optional when using mutable or other specifiers.
Under the Hood: The Closure Object
To understandmutable, you must examine the compiler-generated class (the closure type) created for the lambda.
Default Lambda (Non-Mutable)
When you capture a variable by value withoutmutable:
Mutable Lambda
When you apply themutable keyword:
const qualifier is stripped from the operator():
Technical Characteristics and Edge Cases
- State Persistence: Because
mutablemodifies the member variables of the closure object itself, the mutated state persists across multiple invocations of the same lambda instance.
- Isolation from Enclosing Scope: Mutating a by-value capture only alters the closure object’s internal copy. The original variable in the enclosing scope remains completely unchanged.
- Top-Level
constVariables: If a variable is declared with a top-levelconstin the enclosing scope, capturing it by value copies theconstqualifier directly to the closure’s internal data member. In this scenario, applyingmutablestrips theconstfromoperator(), but the internal variable itself remains aconsttype and cannot be modified.
- Irrelevance to Reference Captures: The
mutablekeyword has no practical effect on variables captured by reference ([&],[&x]). A reference capture allows modification of the original variable regardless of whether the lambda ismutable, because theconstqualification of the defaultoperator()applies to the reference itself (which is inherently immutable in what it points to), not the referenced data.
Master C++ with Deep Grasping Methodology!Learn More





