Zeb*_*ish 4 c++ lambda static capture
这看起来很奇怪,我可以捕获静态变量,但只有在捕获列表中没有指定变量时,即它会隐式捕获它.
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;
}
Run Code Online (Sandbox Code Playgroud)
我不明白,第三和第四次捕获应该是等价的,不是吗?在第三个我没有捕获具有"自动存储持续时间"的变量
编辑:我认为答案是它永远不会捕获静态变量,所以:
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.
Run Code Online (Sandbox Code Playgroud)
不需要捕获具有静态存储持续时间的变量,因此无法捕获该变量.你可以在lambda中简单地使用它.
使用自动变量存在一个问题:在其他语言中,闭包只是在封闭范围内存储对变量的引用,在C++中,lambda无法延长自动变量的生命周期,因此可能会出现范围,在lambda中留下悬空参考.因此,C++允许您选择是通过复制还是通过引用捕获自动变量.但如果变量是静态的,则不会出现此问题; lambda的行为就像是通过引用捕获它一样.
如果您确实希望按值捕获静态变量,请使用C++ 14 init-capture语法.