Mutating Lambda Member Variables
Explore how to use the mutable keyword in C++ lambdas to enable mutation of member variables despite the default const nature of their call operator. Understand the differences between capture by value and capture by reference, and how these affect variable mutation. Learn practical examples and best practices for capturing variables effectively with lambdas to improve code clarity and behavior.
We'll cover the following...
Using the mutable keyword in lambdas
As the lambda works just like a class with member variables, it can also mutate them. However, the function call operator of a lambda is const by default, so we explicitly need to specify that the lambda can mutate its members by using the mutable keyword. In the following example, the lambda mutates the counter variable every time it's invoked:
If a lambda only captures variables by reference, we do not have to add the mutable modifier to the declaration, as the lambda itself doesn't mutate. The ...