c++ - 无法在 lambda 中捕获静态变量

标签 c++ lambda static capture

<分区>

这看起来很奇怪,我可以捕获静态变量,但前提是该变量未在捕获列表中指定,即它隐式捕获它。

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 语法。

关于c++ - 无法在 lambda 中捕获静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45930423/

相关文章:

c++ - 如何在 C++11 类的位集中有效地支持 "sub-bitstrings"?

c++ - 在同一个类的静态函数中创建一个类的实例是未定义的行为吗

c++ - std::remove_reference 有什么意义

c# - 遍历表达式树并提取参数

c# - 从另一个类调用变量

android - 如何使用 Android 调试桥 (ADB) 更改静态 IP 地址?

c++ - 寻找 OpenCV 教程

c++ - 使用 Qt C++ 写入文本文件

lambda - 如何仅使用 lambda 表达式在 Racket(或 Scheme)中编写等于谓词

php - 后代中的静态变量赋值会冒泡到父级吗?