未检测到未使用的变量

BЈо*_*вић 6 c++ gcc g++ gcc-warning

我使用g ++ 4.3.0编译这个例子:

#include <vector>

int main()
{
  std::vector< int > a;
  int b;
}
Run Code Online (Sandbox Code Playgroud)

如果我用最大警告级别编译示例,我会收到一个警告:不使用变量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]$
Run Code Online (Sandbox Code Playgroud)

问题是:为什么变量a没有报告为未使用?我必须传递哪些参数才能获得变量a的警告?

fre*_*low 23

从理论上讲,默认构造函数std::vector<int>可能有任意的副作用,因此编译器无法弄清楚删除定义是否a会改变程序的语义.您只能获得内置类型的警告.

一个更好的例子是锁:

{
    lock a;
    // ...
    // do critical stuff
    // a is never used here
    // ...
    // lock is automatically released by a's destructor (RAII)
}
Run Code Online (Sandbox Code Playgroud)

即使a在定义之后从未使用过,但删除第一行也是错误的.