Mutating Lambda Member Variables
Understand mutating lambda member variables, their behavior from the compiler's perspective and the use of capture.
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:
Press + to interact
auto counter_func = [counter = 1]() mutable{std::cout << counter++;};counter_func(); // Output: 1counter_func(); // Output: 2counter_func(); // Output: 3
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 difference ...