Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When "this" is captured by a lambda, does it have to be used explicitly?

The examples I have found that capture this in a lambda use it explicitly; e.g.:

capturecomplete = [this](){this->calstage1done();}; 

But it seems it is also possible to use it implicitly; e.g.:

capturecomplete = [this](){calstage1done();}; 

I tested this in g++, and it compiled.

Is this standard C++? (and if so, which version), or is it some form of extension?

like image 439
plugwash Avatar asked Nov 11 '19 15:11

plugwash


People also ask

What does it mean to lambda capture this?

The lambda is capturing an outside variable. 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 in lambda?

Capture clause A lambda can introduce new variables in its body (in C++14), and it can also access, or capture, variables from the surrounding scope. A lambda begins with the capture clause. It specifies which variables are captured, and whether the capture is by value or by reference.

Are lambda captures const?

By default, variables are captured by const value . This means when the lambda is created, the lambda captures a constant copy of the outer scope variable, which means that the lambda is not allowed to modify them.

What is capture clause in lambda function in C++?

A capture clause of lambda definition is used to specify which variables are captured and whether they are captured by reference or by value. An empty capture closure [ ], indicates that no variables are used by lambda which means it can only access variables that are local to it.


1 Answers

It is standard and has been this way since C++11 when lambdas were added. According to cppreference.com:

For the purpose of name lookup, determining the type and value of the this pointer and for accessing non-static class members, the body of the closure type's function call operator is considered in the context of the lambda-expression.

struct X {     int x, y;     int operator()(int);     void f()     {         // the context of the following lambda is the member function X::f         [=]()->int         {             return operator()(this->x + y); // X::operator()(this->x + (*this).y)                                             // this has type X*         };     } }; 
like image 188
Ayxan Haqverdili Avatar answered Sep 27 '22 21:09

Ayxan Haqverdili