无法捕捉到一个lamba中的静态变量

问题描述:

这似乎很奇怪,我可以捕获静态变量,但前提是该变量未在捕获列表中指定,即隐式捕获它。无法捕捉到一个lamba中的静态变量

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. 
+0

([通过在C++ 11拉姆达参考捕捉静态变量]的可能的复制https://stackoverflow.com/questions/13827855/capturing-a-static-variable-by-reference-in -a-c11-lambda) –

具有可变静态存储时间不需要被捕获,因此不能被捕获。你可以简单地在lambda中使用它。

使用自动变量存在一个问题:在其他语言中,闭包会简单地在封闭范围中存储对变量的引用,在C++中,lambda不具有延长自动变量生命周期的能力,因此可能会超出范围,在lambda中留下一个悬而未决的参考。为此,C++允许您选择是通过复制还是通过引用来捕获自动变量。但是如果变量是静态的,那么这个问题就不会出现;拉姆达只会表现得像通过引用捕获它一样。

如果您确实想要通过捕获静态变量,请使用C++ 14 init-capture语法。

+0

“不需要被捕获,因此不能被捕获。” 我在这里看不到逻辑。为什么禁止显式静态变量捕获,如果它无缝地适合C++语言规则 –

+0

@ sfk92fksdf我无法告诉你。委员会中的某个人可能会知道答案。 – Brian

+1

@ sfk92fksdf有你正在寻找的答案:https://stackoverflow.com/a/13828144/2865757 – Zefick

这不是你想要的吗?

static int dont_capture_me = 0; 

auto foo = [] { dont_capture_me++; }; 

当然,你可以明确地存储一个引用,但它们本质上是等价的。

auto bar = [&reference = dont_capture_me] { reference++; };