这看起来很奇怪,我可以捕获静态变量,但只有在捕获列表中没有指定变量时,即它会隐式捕获它。
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 :(得分:7)
不需要捕获具有静态存储持续时间的变量,因此无法捕获该变量。你可以在lambda中使用它。
使用自动变量存在一个问题:在其他语言中,闭包只是在封闭范围内存储对变量的引用,在C ++中,lambda无法延长自动变量的生命周期,这可能是因此超出范围,在lambda中留下悬空参考。因此,C ++允许您选择是通过复制还是通过引用捕获自动变量。但如果变量是静态的,则不会出现此问题; lambda的行为就像它通过引用捕获它一样。
如果您确实希望通过 value 捕获静态变量,请使用C ++ 14 init-capture语法。
答案 1 :(得分:0)
这不是你想要的吗?
static int dont_capture_me = 0;
auto foo = [] { dont_capture_me++; };
当然,您可以显式存储引用,但它们本质上是等效的。
auto bar = [&reference = dont_capture_me] { reference++; };