无法在Lambda中捕获静态变量 [英] Can't capture a static variable in a lambda
问题描述
这似乎很奇怪,我可以捕获静态变量,但前提是在捕获列表中未指定该变量,即隐式捕获它。
This seems strange, I can capture the static variable, but only if the variable isn't specified in the capture list, i.e., it implicitly captures it.
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;
}
我不理解,第三个和第四次捕获应该是等效的,不是吗?在第三次中,我不是捕获具有自动存储持续时间的变量
I'm not understanding, the third and fourth captures should be equivalent, no? In the third I'm not capturing a variable with "automatic storage duration"
编辑:我认为答案是这样的永远不会捕获静态变量,所以:
I think the answer to this is that it is never capturing the static variable, so:
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中简单地使用它。
A variable with static storage duration doesn't need to be captured, and, therefore, cannot be captured. You can simply use it within the lambda.
对于自动变量,存在一个问题:而在其他语言中,闭包仅将对变量的引用存储在封闭范围内,在C ++中,lambda无法延长自动变量的生存期,因此可能超出范围,从而在lambda中留下了悬挂的引用。因此,C ++允许您选择是通过复制还是通过引用捕获自动变量。但是,如果变量是静态的,则不会出现此问题。该lambda的行为就像是通过引用捕获它一样。
With automatic variables there is an issue: while in other languages a closure would simply store a reference to the variable in the enclosing scope, in C++ a lambda does not have the ability to extend the lifetime of an automatic variable, which might therefore go out of scope, leaving behind a dangling reference in the lambda. For this reason C++ allows you to choose whether to capture an automatic variable by copy or by reference. But if the variable is static then this issue does not arise; the lambda will simply behave as though it has captured it by reference.
如果您确实想通过 value 捕获静态变量,请使用C ++ 14初始化捕获语法。
If you do want to capture a static variable by value then use the C++14 init-capture syntax.
这篇关于无法在Lambda中捕获静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!