2011-10-19 53 views
8

考虑下面的代码:为什么我无法通过lambda捕获“this”指针?

class A 
{ 
public: 
    void foo() 
    { 
     auto functor = [this]() 
      { 
       A * a = this; 
       auto functor = [a]() // The compiler won't accept "this" instead of "a" 
        { 
         a->bar(); 
        }; 
      }; 
    } 

    void bar() {} 
}; 

在VC2010,使用this代替a导致编译错误。其中包括:

1>main.cpp(20): error C3480: '`anonymous-namespace'::<lambda0>::__this': a lambda capture variable must be from an enclosing function scope 
1>main.cpp(22): error C3493: 'this' cannot be implicitly captured because no default capture mode has been specified 

我不明白。这是否意味着它不知道应该使用引用还是复制它?当试图使用&this强制引用,它也说:

1>main.cpp(20): error C3496: 'this' is always captured by value: '&' ignored 

暂时不说讨厌,但对于好奇的缘故,有没有办法摆脱它的方法吗? this给lambda时什么发生?

+2

即使使用'[this]',GCC 4.6.1也能正常工作。 –

+0

@KerrekSB相关知识...感谢您的测试! – Gabriel

+4

这看起来像[bug#560907](https://connect.microsoft.com/VisualStudio/feedback/details/560907/capturing-variables-in-nested-lambdas)(不幸的是,以'WONTFIX'关闭)。 –

回答

6

这似乎是VS2010中的一个编译器错误。我能够让它通过让内部拉姆达工作含蓄地捕捉this

class A 
{ 
public: 
    void foo() 
    { 
     auto functor = [this]() 
     { 
      auto functor = [=]() 
      { 
       bar(); 
      }; 
     }; 
    } 

    void bar() {} 
}; 

当尝试使用&这迫使引用,它也说:

1>主。 cpp(20):错误C3496:'this'总是被值捕获:'&'忽略

this只能被值捕获。 [=][&]都是通过值来捕获它。

这是什么时候给lambda?

我不知道,但它必须是一些特别的东西,因为你不能在一个lambda使用this作为指针拉姆达对象。其他拍摄成为拉姆达的私人成员,所以大概this也做,但有一些特殊的使用处理。

相关问题