1

I am trying to move a vector into a lambda, but I get a compile error:

std::vector<int> vec {1,2,3};
auto lambda = [vec2 = std::move(vec)](){
     vec2.push_back(1);
}

The error is error C2663: "2 overloads have no legal conversion for 'this' pointer" It is generated in the line vec2.push_back(1)

when I change the example to

std::vector<int> vec {1,2,3};
auto lambda = [vec2 = std::move(vec)](){
     auto vec3 = std::move(vec2);
     vec3.push_back(1);
}

it compiles and works.

So is this behavior correct and if so, why can vec2 not be modified?

Knitschi
  • 2,822
  • 3
  • 32
  • 51
  • 2
    Use `mutable`, so that lambda call is not const. – Zereges Sep 23 '16 at 06:57
  • So after a quick search (see [here](http://stackoverflow.com/questions/5501959/why-does-c0xs-lambda-require-mutable-keyword-for-capture-by-value-by-defau)) I see that this has nothing to do with the move capture but is always the case when capturing by value. Very strange that after all this time of using lambdas it is only now that I encounter the behavior. – Knitschi Sep 23 '16 at 07:03
  • If you copy the example with the mutable keyword in it into an answer I will give you the points ;-) – Knitschi Sep 23 '16 at 07:05

1 Answers1

1

The issue with your code does not have to do anything with generalized lambda capture. By default, lambda's call operator is const and thus, objects captured by lambda will be treated as const. You can use mutable keyword. That will make lambda's call operator non-const allowing you to modify captured objects.

std::vector<int> vec {1,2,3};
auto lambda = [vec2 = std::move(vec)]() mutable {
     vec2.push_back(1); //              ^ note
}
Zereges
  • 5,139
  • 1
  • 25
  • 49