user8024280
user8024280

Reputation:

Lambda`s internal this in c++

If lambda function ic C++ is implemented by functor, why this is not possible?

#include <iostream>

class A
{
public: 
    int a;  
    void f1(){ [](){std::cout << this << std::endl ;}();};
};

int main()
{
    A a;
    a.f1();
}

I get error 9:34: error: 'this' was not captured for this lambda function. If I understand it right, if lambda is implemented as a functor class, why it is not possible to get it`s internal this?

EDIT: this of functor class, not this of instance of class A.

Upvotes: 1

Views: 251

Answers (1)

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

From lambda:

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

So, it is impossible to reference this as you wish.

Upvotes: 7

Related Questions