[英]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.