gpt4 book ai didi

c++ - 非本地 lambda 和捕获变量 - "block scope"是什么意思

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

我目前正在玩 c++11 lambda,发现了一个我无法理解的例子。根据标准:

A lambda-expression whose smallest enclosing scope is a block scope (3.3.3) is a local lambda expression; any other lambda-expression shall not have a capture-list in its lambda-introducer

所以,我创建了一个简单的例子:

int a = 10;
auto x = [a] { return 1;};
int main() {
int k = 5;
auto p = [k]{ return k; };
return 0;
}

ideone中的代码:http://ideone.com/t9emu5

我原以为这段代码不会编译,因为在非 block 范围内捕获变量(或者至少认为 auto x = ... 部分不在 block 范围内)。但是代码正在编译 - 可以吗?

如果可以 - block 作用域是什么?

(我不确定我使用的编译器版本,因为目前我只能访问 ideone 站点。

感谢您的解释!

最佳答案

看起来这是一个编译器扩展。 g++4.8.1 在给出警告的同时编译它:

warning: capture of variable ‘a’ with non-automatic storage duration [enabled by default]

clang++3.4 不编译这个:

error: 'a' cannot be captured because it does not have automatic storage duration

均指[expr.prim.lambda]/10

The identifiers in a capture-list are looked up using the usual rules for unqualified name lookup (3.4.1); each such lookup shall find a variable with automatic storage duration declared in the reaching scope of the local lambda expression.

他们似乎没有额外检查 lambda 的封闭范围,我可以想象这将是多余的(在非 block /命名空间范围内没有具有自动存储持续时间的变量名称)。


block 作用域定义在[basic.scope.block]/1

A name declared in a block (6.3) is local to that block; it has block scope.

一个 block 定义为:

So that several statements can be used where one is expected, the compound statement (also, and equivalently, called “block”) is provided.

     compound-statement:
         { statement-seqopt }

所以您是对的,您的全局声明的 lambda 在 block 范围内。

关于c++ - 非本地 lambda 和捕获变量 - "block scope"是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19344955/

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