Search code examples
c++lambdathis-pointer

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?


Solution

  • 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*
            };
        }
    };