gpt4 book ai didi

c++ - 区分黑白捕获的 `this` 成员与 C++ lambda 中捕获的变量

转载 作者:行者123 更新时间:2023-11-30 05:08:32 24 4
gpt4 key购买 nike

我想知道 C++ 中 lambda 的捕获。我知道 lambda 表达式只是某些仿函数类的“生成器”。我想知道编译器如何区分成员与捕获的“this”与生成的仿函数类的成员?

第二个问题:

在下面的示例中,a_ 来自捕获列表阴影 A::a_。标准中描述了这种行为吗?我在任何地方都找不到答案。

class A {
int a_ = 0;
public:
void sth() {
auto l = [this, a_=1](int a) { a_ = a; };
l(1);
}
};

最佳答案

分解它(并修复错误):

class A {
int a_ = 0; // this is A::a_
public:
void sth() {
auto l =
[
this, // A::sth::lambda::l::_this
a_=a_ // A::sth::lambda::l::a_ = A::a_ // because the lambda's a_ does not exist until it's defined.
](int a) mutable
{
a_ = a; // A::sth::lambda::l::a_ = argument a
};
l(1);
}
};

关于c++ - 区分黑白捕获的 `this` 成员与 C++ lambda 中捕获的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46810236/

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