未检测到未使用的变量
我正在使用 g++ 4.3.0 编译此示例:
#include <vector>
int main()
{
std::vector< int > a;
int b;
}
如果我使用最大警告级别编译该示例,我会收到一条警告,指出未使用变量 b :
[vladimir@juniper data_create]$ g++ m.cpp -Wall -Wextra -ansi -pedantic
m.cpp: In function ‘int main()’:
m.cpp:7: warning: unused variable ‘b’
[vladimir@juniper data_create]$
问题是:为什么变量 a 没有报告为未使用? 我必须传递哪些参数才能获取变量 a 的警告?
I am using g++ 4.3.0 to compile this example :
#include <vector>
int main()
{
std::vector< int > a;
int b;
}
If I compile the example with maximum warning level, I get a warning that the variable b is not used :
[vladimir@juniper data_create]$ g++ m.cpp -Wall -Wextra -ansi -pedantic
m.cpp: In function ‘int main()’:
m.cpp:7: warning: unused variable ‘b’
[vladimir@juniper data_create]$
The question is : why the variable a is not reported as not used?
What parameters do I have to pass to get the warning for the variable a?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
理论上,
std::vector
的默认构造函数可能会产生任意副作用,因此编译器无法确定删除a
的定义是否会改变语义的程序。您只会收到内置类型的警告。一个更好的例子是锁:
即使
a
在定义后从未使用过,删除第一行也是错误的。In theory, the default constructor for
std::vector<int>
could have arbitrary side effects, so the compiler cannot figure out whether removing the definition ofa
would change the semantics of the program. You only get those warning for built-in types.A better example is a lock:
Even though
a
is never used after its definition, removing the first line would be wrong.a 实际上是在声明后使用的,因为它的析构函数在其作用域末尾被调用。
a is actually used after it is declared as its destructor gets called at the end of its scope.
a 不是内置类型。您实际上是在调用 std::vector的构造函数并将结果分配给 a。编译器将此视为用法,因为构造函数可能会产生副作用。
a is not a built-in type. You are actually calling the constructor of
std::vector<int>
and assigning the result to a. The compiler sees this as usage because the constructor could have side effects.