This seems strange, I can capture the static variable, but only if the variable isn't specified in the capture list, i.e., it implicitly captures it.
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;
}
I'm not understanding, the third and fourth captures should be equivalent, no? In the third I'm not capturing a variable with "automatic storage duration"
Edit: I think the answer to this is that it is never capturing the static variable, so:
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.
                A variable with static storage duration doesn't need to be captured, and, therefore, cannot be captured. You can simply use it within the lambda.
With automatic variables there is an issue: while in other languages a closure would simply store a reference to the variable in the enclosing scope, in C++ a lambda does not have the ability to extend the lifetime of an automatic variable, which might therefore go out of scope, leaving behind a dangling reference in the lambda. For this reason C++ allows you to choose whether to capture an automatic variable by copy or by reference. But if the variable is static then this issue does not arise; the lambda will simply behave as though it has captured it by reference.
If you do want to capture a static variable by value then use the C++14 init-capture syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With