Alex Botev
Alex Botev

Reputation: 1399

C++ lambda capture - which get's captured?

So I have the expression below inside a class, following definitions:

std::vector<std::function<MyClass (const MyClass&)>> funcVec;
result->funcVec.push_back([=](const MyClass& child){
                return this->funcVec[i](child);
            });

(E.g. copy the lambda evaluation of (this) to the result instance)

The qustion is that I'm not sure which is captured by value - the whole object (this),potentially i or just the function (ths->funcVec[i])?

Any extra explanations and recommendation of why not to use this make it better, or confirmation that this is ok are more than welcome.

Upvotes: 0

Views: 103

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254471

The things that can be captured are local automatic variables, by value or reference, and the pointer this, by value only. Your lambda uses i and this, so they are captured (assuming i is a local variable). You specified a default capture by value, [=], so both are captured by value.

This is fine as long as the object *this still exists when the lambda is called.

Upvotes: 6

Related Questions