【发布时间】:2014-06-24 13:58:18
【问题描述】:
在 node.js 中,我可以在 lambda 中编写 lambda 并捕获我想要的任何变量。但在 C++11 中,由于 lambda 函数实际上是函子对象,因此使用嵌套的 lambda 捕获变量并不那么容易。
我正在使用[this] 来捕获此指针,以便我可以使用类成员。但在 lambda 内部,this 指针指向 lambda 而不是外部类。
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?
【问题讨论】:
-
@BЈовић 为什么通过复制隐式捕获
this比通过复制显式捕获它“更好”? -
@Casey 我的错。我的意思是
[&] -
@BЈовић 通过引用捕获
this是没有意义的,因为它是prvalue。事实上,该标准不允许通过引用显式捕获this:[&this]和[=,this]都被明确禁止。允许通过引用隐式捕获this可能是标准中的错误。编译器将隐式引用捕获视为按副本捕获。 (更多讨论请参见restriction about default capture mode and 'this' in C++ lambda-expression。)