当lambda捕获“ ​​this”时,是否必须显式使用它?

plu*_*ash 26 c++ lambda this-pointer

我发现this在lambda 中捕获的示例显式使用了它。例如:

capturecomplete = [this](){this->calstage1done();};
Run Code Online (Sandbox Code Playgroud)

但是似乎也可以隐式使用它。例如:

capturecomplete = [this](){calstage1done();};
Run Code Online (Sandbox Code Playgroud)

我在g ++中对此进行了测试,并对其进行了编译。

这是标准的C ++吗?(如果可以,是哪个版本),还是某种扩展形式?

Ayx*_*xan 24

这是标准的,并且从C ++ 11开始添加lambda以来一直采用这种方式。根据cppreference.com

为了进行名称查找,确定this指针的类型和值 以及访问非静态类成员,在lambda表达式的上下文中考虑了闭包类型的函数调用运算符的主体。

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*
        };
    }
};
Run Code Online (Sandbox Code Playgroud)


Lig*_*ica 18

自从Lambdas在C ++ 11中引入以来,它是完全标准的

您不需要在this->那里写。