这看起来很奇怪,我可以捕获静态变量,但前提是该变量未在捕获列表中指定,即它隐式捕获它。
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.
具有静态存储持续时间的变量不需要捕获,因此无法捕获。您可以简单地在 lambda 中使用它。
自动变量存在一个问题:在其他语言中,闭包只会在封闭范围内存储对变量的引用,而在 C++ 中,lambda 无法延长自动变量的生命周期,因此可能会消失范围,在 lambda 中留下悬空引用。因此,C++ 允许您选择是通过复制还是通过引用捕获自动变量。但如果变量是静态的,那么这个问题就不会出现; lambda 的行为就像通过引用捕获它一样。
如果您确实想通过以下方式捕获静态变量value然后使用 C++14 init-capture 语法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)