Why can't I grab the "this" lambda pointer?

Consider the following code:

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() {} }; 

In VC2010, using this instead of a leads to compilation errors. Among other things:

 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 

What? I do not understand. Does this mean that he does not know whether to use the link or copy it? When trying to use &this to force binding, it also says:

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

Temporary is not something that annoys, but for the sake of curiosity, is there a way to get rid of it? What happens when this provided lambda?

+8
c ++ lambda this c ++ 11
source share
2 answers

This is similar to a compiler error in VS2010. I was able to make it work, allowing the inner lambda to implicitly capture this :

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

When trying to use & to force binding, it also says:

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

this can only be fixed by value. [=] and [&] both capture it by value.

What happens when it is given lambda?

I don’t know, but it must be something special, because you cannot use this in lambda as a pointer to a lambda object. Any other captured will become a private member of the lambda, so this supposedly the same, but there is special handling when using it.

+6
source share

This is a known bug with the Visual Studio 2010 compiler (as referenced by Frederick Hamidi's comment).

You must explicitly write this to pass it to another lamba capture specification. This also applies to local variables declared outside of lambda-lambda, even using the [&] specification.

+2
source share

All Articles