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

c – 可以使用lambda捕获全局变量吗?,第1张

概述int n; int main(){ [](){ n = 0; }(); // clang says "ok" int m; [](){ m = 0; }(); // clang says "not ok"} 我只是好奇: 如果lambda没有捕获任何东西,是否允许根据C标准访问全局变量? 是的,当然.正常名称查找规则适用. [expr.prim.lambda
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不是,所以不一定是.

总结

以上是内存溢出为你收集整理的c – 可以使用lambda捕获全局变量吗?全部内容,希望文章能够帮你解决c – 可以使用lambda捕获全局变量吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1255260.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存