Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

lambda

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();
       }
    }
}
like image 926
Emerald Weapon Avatar asked Jul 01 '16 10:07

Emerald Weapon


People also ask

What does it mean to lambda capture this?

A lambda is a syntax for creating a class. Capturing a variable means that variable is passed to the constructor for that class. A lambda can specify whether it's passed by reference or by value.

How do you capture a variable in lambda function?

Much like functions can change the value of arguments passed by reference, we can also capture variables by reference to allow our lambda to affect the value of the argument. To capture a variable by reference, we prepend an ampersand ( & ) to the variable name in the capture.

What is a lambda capture list?

The capture list defines the outside variables that are accessible from within the lambda function body. The only capture defaults are. & (implicitly capture the used automatic variables by reference) and. = (implicitly capture the used automatic variables by copy).

Can we use this keyword in lambda?

The "this" and "super" references within a lambda expression are the same as in the enclosing context. Since the lambda expression doesn't define a new scope, "this" keyword within a lambda expression signifies "this" parameter of a method where the lambda expression is residing.


1 Answers

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!

like image 200
underscore_d Avatar answered Sep 28 '22 15:09

underscore_d