相关疑难解决方法(0)

为什么我不能在lambda中捕获这个by-reference('&this')?

我理解this在lambda中捕获(修改对象属性)的正确方法如下:

auto f = [this] () { /* ... */ };
Run Code Online (Sandbox Code Playgroud)

但我很好奇我所看到的以下特点:

class C {
    public:
        void foo() {
            // auto f = [] () { // this not captured
            auto f = [&] () { // why does this work?
            // auto f = [&this] () { // Expected ',' before 'this'
            // auto f = [this] () { // works as expected
                x = 5;
            };
            f();
        }

    private:
        int x;
};
Run Code Online (Sandbox Code Playgroud)

我很困惑的奇怪(并希望得到回答)是以下工作的原因:

auto f = …
Run Code Online (Sandbox Code Playgroud)

c++ lambda c++11

74
推荐指数
2
解决办法
6万
查看次数

标签 统计

c++ ×1

c++11 ×1

lambda ×1