Knitschi
Knitschi

Reputation: 3102

Generalized Lambda Capture Expressions in Visual Studio 2015: Compiler bug or correct behavior?

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?

Upvotes: 1

Views: 628

Answers (1)

Zereges
Zereges

Reputation: 5209

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
}

Upvotes: 1

Related Questions