In node.js I can write lambda inside lambda and capture whichever variable I want. But in C++11, as lambda functions are actually functor object, variable capturing is not so easy with nested lambdas.
I'm using [this] to capture this pointer so I can use class members. But inside a lambda, this pointer points to the lambda instead of the outter class.
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
});
});
}
I know it can be done by rename this to another pointer variable and capture that variable instead of this, but I think that way is ugly.
Is there any better way to capture outter this?
thisimplicitly by copy be in any way "better" than capturing it explicitly by copy?[&]thisby reference since it is a prvalue. Indeed, the standard does not allow explicitly capturingthisby reference: both[&this]and[=,this]are explicitly forbidden. Allowing implicit capture ofthisby reference is probably an error in the standard. Compilers treat implicit reference capture as capture by copy. (See restriction about default capture mode and 'this' in C++ lambda-expression for more discussion.)