Is it bad practice to make lambdas mutable?

Viewed 109

The following lambda doesn't compile:

auto l = [a = std::vector<int>() ]  {
                        a.resize(1);
                    } ;

That is because the variable captured by value a is automatically typed as const. The following lambda should compile (although it doesn't on Visual Studio 2019 apparently):

 auto l = [a = std::vector<int>() ] mutable {
                        a.resize(1);
                    } ;

What is the rationale for transforming a into a const vector automatically in the first place ? It feels like I'm doing something wrong by forcing the lambda to be mutable. Was this done to prevent accidentally modifying the closure parameters in case I want to execute the lambda several times?

0 Answers
Related