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

c – 无法捕获lamba中的静态变量

发布时间:2020-12-16 10:07:45 所属栏目:百科 来源:网络整理
导读:这看起来很奇怪,我可以捕获静态变量,但只有在捕获列表中没有指定变量时,即它会隐式捕获它. int main(){ int captureMe = 0; static int captureMe_static = 0; auto lambda1 = []() { captureMe++; }; // Works,deduced capture auto lambda2 = [captureMe](
这看起来很奇怪,我可以捕获静态变量,但只有在捕获列表中没有指定变量时,即它会隐式捕获它.

int main()
{
    int captureMe = 0;
    static int captureMe_static = 0;

    auto lambda1 = [&]() { captureMe++; };  // Works,deduced capture
    auto lambda2 = [&captureMe]() { captureMe++; }; // Works,explicit capture
    auto lambda3 = [&] () { captureMe_static++; };  // Works,capturing static int implicitly
    auto lambda4 = [&captureMe_static] { captureMe_static++; }; // Capturing static in explicitly:  
                                                                // Error: A variable with static storage duration 
                                                                // cannot be captured in a lambda

    // Also says "identifier in capture must be a variable with automatic storage duration declared
    // in the reaching scope of the lambda

    lambda1(); lambda2(); lambda3();    // All work fine

    return 0;
}

我不明白,第三和第四次捕获应该是等价的,不是吗?在第三个我没有捕获具有“自动存储持续时间”的变量

编辑:我认为答案是它永远不会捕获静态变量,所以:

auto lambda = [&] { captureMe_static++; };   // Ampersand says to capture any variables,but it doesn't need to capture anything so the ampersand is not doing anything
auto lambda = [] { captureMe_static++; };  // As shown by this,the static doesn't need to be captured,and can't be captured according to the rules.

解决方法

不需要捕获具有静态存储持续时间的变量,因此无法捕获该变量.你可以在lambda中简单地使用它.

使用自动变量存在一个问题:在其他语言中,闭包只是在封闭范围内存储对变量的引用,在C中,lambda无法延长自动变量的生命周期,因此可能会出现范围,在lambda中留下悬空参考.因此,C允许您选择是通过复制还是通过引用捕获自动变量.但如果变量是静态的,则不会出现此问题; lambda的行为就像是通过引用捕获它一样.

如果您确实想要按值捕获静态变量,请使用C 14 init-capture语法.

(编辑:李大同)

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

    推荐文章
      热点阅读