What is a mutable lambda?
Short answer
By default, a lambda's operator() is const, so by-value captured variables can't be modified inside the body.
Advertisement
AModel answer
By default, a lambda's operator() is const, so by-value captured variables can't be modified inside the body. Marking the lambda mutable removes the const, allowing modification of the by-value copies (the changes persist across calls to that lambda instance but don't affect the originals).
int n = 0;
auto counter = [n]() mutable { return ++n; };
counter(); counter(); // returns 1, then 2Real-world example
A mutable lambda maintains an internal counter across calls without an external variable.
Likely follow-ups
- Why is operator() const by default? | Do mutable changes affect the original?
Related topics