加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 可以使用lambda捕获全局变量吗?

发布时间:2020-12-16 03:23:19 所属栏目:百科 来源:网络整理
导读:int n; int main(){ [](){ n = 0; }(); // clang says "ok" int m; [](){ m = 0; }(); // clang says "not ok"} 我只是好奇: 如果lambda没有捕获任何东西,是否允许根据C标准访问全局变量? 解决方法 是的,当然.正常名称查找规则适用. [expr.prim.lambda]/7
int n;    
int main()
{
    [](){ n = 0; }(); // clang says "ok"

    int m;
    [](){ m = 0; }(); // clang says "not ok"
}

我只是好奇:

如果lambda没有捕获任何东西,是否允许根据C标准访问全局变量?

解决方法

是的,当然.正常名称查找规则适用.

[expr.prim.lambda]/7 … for purposes of name lookup … the compound-statement is considered in the context of the lambda-expression.

Re:为什么局部变量与全局变量不同.

[expr.prim.lambda]/13 … If a lambda-expression or an instantiation of the function call operator template of a generic lambda odr-uses (3.2) this or a variable with automatic storage duration from its reaching scope,that entity shall be captured by the lambda-expression.

[expr.prim.lambda]/9 A lambda-expression whose smallest enclosing scope is a block scope (3.3.3) is a local lambda expression… The reaching scope of a local lambda expression is the set of enclosing scopes up to and including the innermost enclosing function and its parameters.

在你的例子中,m是一个变量,它具有从lambda到达范围的自动存储持续时间,因此将被捕获. n不是,所以不一定是.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读