7

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?

lezebulon
  • 7,607
  • 11
  • 42
  • 73
  • case (2) needs to be `auto l = [a = std::vector() ] () mutable { a.resize(1); } ;` - live - https://godbolt.org/z/szjrjbeGv – Richard Critten Dec 15 '21 at 11:11
  • 4
    Maybe [this](https://stackoverflow.com/a/21228590/7703564) answer gives some insights on the issue of mutable lambdas. – Jodocus Dec 15 '21 at 11:12
  • 1
    There are nothing wrong to have no `const` methods/objects. It is just that, in C++ the default, except for lambda, is mutable instead of `const`. – Jarod42 Dec 15 '21 at 11:20

0 Answers0