Search⌘ K
AI Features

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.

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:

C++ 17
auto counter_func = [counter = 1]() mutable
{
std::cout << counter++;
};
counter_func(); // Output: 1
counter_func(); // Output: 2
counter_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 ...