为什么未捕获的变量会发出警告? [英] Why non-captured variable is raising warning?
问题描述
在VS 2015 中考虑以下代码:
Consider this code in VS2015:
int a,b;
[]
{
int a; // C4456: declaration of 'a' hides previous local declaration
};
为什么lambda中的a
发出这样的警告?在VS2013中可以正常编译.
Why a
in lambda giving such warning? It compiles fine in VS2013.
编辑:有趣的是(并且错误地),以下内容在VS2013中不是错误:
Interestingly, (and incorrectly), following is not an error in VS2013:
[a]
{
int a; // No error, even if `a` is captured.
a++;
};
推荐答案
第一个警告肯定看起来像是编译器错误.
The first warning definitely looks like a compiler bug.
第二个不是bug,因为您在不同的范围内声明了它.该变量仅被捕获,捕获未声明.
The second one isn't a bug since you're declaring it in a different scope. The variable is only captured, it is not declared by the capture.
考虑可能会生成的功能对象
Think about the function object this could generate
class foo {
foo(int a): a(a) {}
void operator()() {
int a;
}
int a;
};
a
的两个声明之间没有冲突,并且由于lambda编译为类似这样的内容,所以这就是捕获不关心内部声明的原因.
There's no conflict between the two declarations of a
, and since the lambda compiles to something like this, that's why the capture doesn't care about the inner declaration.
更新:这与
void foo(int a) {
int a;
}
因为使用lambda,它将被编译为带有operator()
的类,并且捕获将作为构造函数参数传入,这就是为什么它们位于不同范围的原因.
because in the case of the lambda, it will get compiled to a class with an operator()
, and the captures will get passed in as constructor parameters, which is why they're in a different scope.
这篇关于为什么未捕获的变量会发出警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!