为什么我无法捕获“此”消息? Lambda指针? [英] Why am I failing to capture the "this" pointer by a lambda?

查看:161
本文介绍了为什么我无法捕获“此”消息? Lambda指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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 导致编译错误。其中:

In VC2010, using this instead of a lead to compilation errors. Among others:

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 强制引用时,它还会说:

Which I don't understand. Does it mean it doesn't know if it should use a reference or copy it? When trying to use &this to force referencing, it also says:

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

临时不是很烦人,但是出于好奇,有办法摆脱它吗?

The temporary is not that annoying, but for the sake of curiosity, is there a way to get rid of it? What goes on when this is given to a lambda?

推荐答案

这是怎么回事?似乎是VS2010中的编译器错误。我能够通过让内部lambda隐式捕获 this

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






尝试使用& this强制引用时,它还说:

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

1> main.cpp(20):错误C3496: this始终由值捕获:&已忽略

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.


将其提供给lambda会发生什么?

What goes on when this is given to a lambda?

我不知道,但这一定是特殊的,因为您不能在lambda中使用 this 作为指向lambda对象的指针。 被捕获的会成为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.

这篇关于为什么我无法捕获“此”消息? Lambda指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆