gpt4 book ai didi

c++ - 为什么我无法通过 lambda 捕获 "this"指针?

转载 作者:可可西里 更新时间:2023-11-01 17:47:04 30 4
gpt4 key购买 nike

考虑以下代码:

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

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

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

临时没有那么烦人,但是出于好奇,有没有办法摆脱它?当 this 被赋予 lambda 时会发生什么?

最佳答案

这似乎是 VS2010 中的编译器错误。我能够通过让内部 lambda 隐式捕获 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 只能按值捕获。 [=][&] 都按值捕获它。

What goes on when this is given to a lambda?

我不知道,但它一定很特别,因为您不能在 lambda 中使用 this 作为指向 lambda 对象的指针。任何其他捕获 都成为 lambda 的私有(private)成员,因此大概 this 也是如此,但对使用有一些特殊处理。

关于c++ - 为什么我无法通过 lambda 捕获 "this"指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7826715/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com