Gab*_*iel 8 c++ lambda this c++11
请考虑以下代码:
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() {}
};
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
哪个我不明白.这是否意味着它不知道它是应该使用引用还是复制它?在尝试使用&this
强制引用时,它还说:
1>main.cpp(20): error C3496: 'this' is always captured by value: '&' ignored
Run Code Online (Sandbox Code Playgroud)
暂时不是那么烦人,但为了好奇,有没有办法摆脱它?什么时候this
给一个lambda?
这似乎是VS2010中的编译器错误.我能够通过让内部lambda隐式捕获它来使它工作this
:
class A
{
public:
void foo()
{
auto functor = [this]()
{
auto functor = [=]()
{
bar();
};
};
}
void bar() {}
};
Run Code Online (Sandbox Code Playgroud)
当试图使用&this强制引用时,它还说:
1> main.cpp(20):错误C3496:'this'始终由值捕获:'&'被忽略
this
只能通过价值捕获.[=]
并且[&]
都按价值捕获它.
当给予lambda时会发生什么?
我不知道但它必须是特殊的东西,因为你不能this
在lambda中使用它作为指向lambda对象的指针.捕获的任何其他内容都成为lambda的私有成员,因此可能this
也会这样做但是在使用时会有一些特殊处理.