C++ 如何捕捉;这";在lambda中的lambda函数中?

C++ 如何捕捉;这";在lambda中的lambda函数中?,c++,c++11,lambda,C++,C++11,Lambda,比如说 class A { void f() {} void g() { [this]() // Lambda capture this { f(); A* p = this; [p]() // Workaround to let inner lambda capture this { p->f();

比如说

class A
{
    void f() {}
    void g()
    {
        [this]() // Lambda capture this
        {
            f();
            A* p = this;
            [p]() // Workaround to let inner lambda capture this
            {
                p->f();
            };
        };
    }
};

是否有更好的方法在内部lambda中捕获此信息?

只需使用
[=]
,这是隐式捕获的。如果您有其他不想通过复制捕获的变量,则只需捕获
[此]

即可重新捕获

class A
{
    void f() {}
    void g()
    {
        [this]()
        {
            f();
            [this]()
        //   ^^^^
            {
                f();
            };
        };
    }
};

为了便于理解,为什么不
[&]
?@bash.d:
只能通过复制来捕获,即
[this]
[=]
@yngum:
是一个PR值(临时值),不能引用临时值。错误信息:
error:“this”无法通过引用捕获
@Jesse Good:,我将其捕获为[&],&a将等同于a.g()。@yngum:即使使用
[&]
,代码也是通过复制隐式捕获
。在我的VS2010中,它不起作用。@user1899020:好的,我不知道你在哪里使用VS2010,所以我没有在那里测试它。我猜VC10中lambdas的实现是不兼容的。@user1899020似乎VS10只支持lambdas V1.0而不支持V1.1,请参见此处。@JesseGood,其他人-这不是另一个问题的重复,因为它与MSV无关。