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();
}
}
}
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.
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.
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).
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With