Why am I failing to capture the “this” pointer by a lambda?

六月ゝ 毕业季﹏ 提交于 2019-12-04 03:39:28

This appears to be a compiler bug in VS2010. I was able to make it work by letting the inner lambda implicitly capture this:

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

    void bar() {}
};

When trying to use &this to force referencing, it also says:

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

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

What goes on when this is given to a lambda?

I don't know but it must be something special because you can't use this in a lambda as a pointer to the lambda object. Anything else captured becomes a private member of the lambda so presumably this does too but there's some special handling on usage.

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

You have to explicitly capture this to pass it to another lamba's capture specification. This also applies to local variables declared outside the lambda's enclosing lambda, even with a [&] capture specification.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!