Emerald Weapon
Emerald Weapon

Reputation: 2540

Using `this->` in a lambda that captures `this`

There are several similar questions out there, but I can't find a definitive answer to this specific point.

Is it completely equivalent to use or not use this-> when calling a method or a member variable within a lambda that captures this, or there is some nuanced difference?

class C {

    int var;
    void foo();

    void fool() {

       auto myLambda = [this] () {
           //
           this->var = 1;
           this->foo();
           // 100% equivalent to?
           var = 1;
           foo();
       }
    }
}

Upvotes: 7

Views: 7093

Answers (2)

Yura
Yura

Reputation: 1

You forgot ';' after declaration lambda.

this->var = 1;
this->foo();
// 100% equivalent to?
var = 1;
foo();

Yes it's equivalent.

Upvotes: 0

underscore_d
underscore_d

Reputation: 6791

Default-capturing [this] both captures the instance pointer and means that name searching within the lambda also includes the class namespace. So, if a matching variable name is found, it refers to that variable in the captured instance (unless shadowed in a closer scope, etc.).

So, yes, using var in this context is equivalent to/shorthand for this->var. Exactly the same as using a member name within a regular instance function!

Upvotes: 15

Related Questions