考虑下面的代码:为什么我无法通过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时什么发生?
即使使用'[this]',GCC 4.6.1也能正常工作。 –
@KerrekSB相关知识...感谢您的测试! – Gabriel
这看起来像[bug#560907](https://connect.microsoft.com/VisualStudio/feedback/details/560907/capturing-variables-in-nested-lambdas)(不幸的是,以'WONTFIX'关闭)。 –