问题
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.
回答1:
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.
回答2:
Isn't this what you wanted?
static int dont_capture_me = 0;
auto foo = [] { dont_capture_me++; };
Of course, you can explicitly store a reference, but they are essentially equivalent.
auto bar = [&reference = dont_capture_me] { reference++; };
来源:https://stackoverflow.com/questions/45930423/cant-capture-a-static-variable-in-a-lambda