これは奇妙なことですが、静的変数をキャプチャできますが、変数がキャプチャリストに指定されていない場合、つまり暗黙的にキャプチャされます。ランバの静的変数をキャプチャできません
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;
}
ノー、第3および第4のキャプチャが同等でなければなりません理解していませんよ?第三に、私は「自動記憶域期間」で変数をキャプチャしていないよ
編集:
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) –