繁体   English   中英

在另一个lambda中包含lambda的C ++ 11变量捕获

[英]C++11 variable capture with lambda inside another lambda

在node.js中,我可以在lambda中编写lambda并捕获我想要的任何变量。 但是在C ++ 11中,由于lambda函数实际上是函子对象,因此使用嵌套lambda捕获变量并不那么容易。

我正在使用[this]捕获此指针,因此可以使用类成员。 但是在lambda中, this指针指向lambda而不是outter类。

void MyClass::myFunction() {
    // call the lambda1
    connect(action, trigger, [this]() {
        // in the lambda1, call lambda2
        sendCommand([this]() {      // <-- I want `this` point to the outter class
            this->myMember.log("something");  // myMember is the member of class MyClass
        });
    });
}

我知道可以通过将其重命名为另一个指针变量并捕获该变量而不是this ,但是我认为这种方式很难看。

有什么更好的方法来捕捉this吗?

但是在lambda中, this指针指向lambda而不是outter类。

不,在lambda内部, this与外部具有相同的值。 在你的代码的唯一问题是访问this. 代替-> 该程序:

void MyClass::myFunction() {
    std::cout << this << std::endl;
    // call the lambda1
    connect(action, trigger, [this]() {
        std::cout << this << std::endl;
        // in the lambda1, call lambda2
        sendCommand([this]() {      // <-- I want `this` point to the outter class
            std::cout << this << std::endl;
            this->myMember.log("something");  // myMember is the member of class MyClass
        });
    });
}

在所有三个位置为此打印相同的值

g++ -std=c++11 -O3 -Wall -Wextra -pedantic -pthread main.cpp && ./a.out
0x7fff4286c80f
0x7fff4286c80f
0x7fff4286c80f

N3936(C ++ 14工作草案)[expr.prim.lambda] / 18指出:

lambda 表达式复合语句中的每个id表达式 (通过副本捕获的实体的odr用法(3.2))都转换为对闭包类型的相应未命名数据成员的访问。 [ 注意:不是odr-use的id表达式是指原始实体,而不是闭包类型的成员。 此外,这种id表达式不会导致隐式捕获实体。 - 注完 ]如果this被捕获,每个ODR使用的this被转换成到闭合型,流延(5.4)到的类型的相应的未命名数据成员的访问this [ 注意:强制类型转换确保转换后的表达式是prvalue。 尾注 ]

您只需捕获外部lambda的上下文:

#include <iostream>

struct Omg
{
  int lol= 42;

  Omg()
  {
    [this]{ [&]{ std::cout<< this-> lol; }(); }();
  }
};

int main(){ Omg(); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM