gpt4 book ai didi

c++ - 内联 lambda 初始化程序可以捕获 'this' 指针吗?

转载 作者:IT老高 更新时间:2023-10-28 21:52:58 25 4
gpt4 key购买 nike

内联成员初始化 lambda 可以捕获和使用 this 指针吗?

struct A{
int a = 42;
int b = [this](){
return this->a * 4;
}();
};

它是有效的 C++11 代码(根据规范)还是只是 GCC 扩展?

如果有效,为什么在引用成员a时必须使用this->

最佳答案

Is it valid c++11 code?

没有。只有 block 范围内的 lambda 可以有捕获列表:

C++11 5.1.2/9 A lambda-expression whose smallest enclosing scope is a block scope is a local lambda expression; any other lambda-expression shall not have a capture-list in its lambda-introducer.

看来这是一个 GCC 扩展。 (如评论中所述,这是一个 open issue ,因此有一天可能会成为标准。)

why I have to use this-> while referring to member a?

至少对于我正在使用的 GCC 版本,您不会:http://ideone.com/K857VC .

关于c++ - 内联 lambda 初始化程序可以捕获 'this' 指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25934368/

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