C++ mutable keyword mutable lambdas

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

By default, the implicit operator() of a lambda is const. This disallows performing non-const operations on the lambda. In order to allow modifying members, a lambda may be marked mutable, which makes the implicit operator() non-const:

int a = 0;

auto bad_counter = [a] {
    return a++;   // error: operator() is const
                  // cannot modify members
};

auto good_counter = [a]() mutable {
    return a++;  // OK
}

good_counter(); // 0
good_counter(); // 1
good_counter(); // 2


Got any C++ Question?