這似乎很奇怪,我可以捕獲靜態變量,但前提是該變量未在捕獲列表中指定,即隱式捕獲它。無法捕捉到一個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.
([通過在C++ 11拉姆達參考捕捉靜態變量]的可能的複製https://stackoverflow.com/questions/13827855/capturing-a-static-variable-by-reference-in -a-c11-lambda) –