Mutating lambda member variables

As the lambda function works just like a class with member variables, it can also mutate them. In the following example, the lambda mutates the threshold variable every time it is invoked.

In order to allow the lambda to mutate its members, we need to specify mutable when declaring the lambda. The mutable modifier on a lambda function works like the inverse for a const modifier for a regular class member function; in contrast to a class member function, a lambda function is const by default, and therefore a mutating lambda must be explicitly specified:

Capture by value

Capture by reference

auto func() {  auto v = 7;  auto lambda = [v]() mutable {    std::cout << v << " ";    ++v;  };  assert(v == 7); lambda(); ...

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.