次のコードを検討してください。なぜ私はラムダによって "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では、a
の代わりにthis
を使用すると、コンパイルエラーが発生します。他の中で:
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
&this
一時的ではありませんが、奇妙なことですが、好奇心のために、それを取り除く方法はありますか? this
がラムダに与えられたらどうなるの?
GCC 4.6.1では '[this]'でもうまく動作します。 –
@KerrekSBお役立ち情報...テストをありがとう! – Gabriel
これは[バグ#560907](https://connect.microsoft.com/VisualStudio/feedback/details/560907/capturing-variables-in-nested-lambdas)(残念ながら 'WONTFIX'として閉じられました)のように見えます。 –