A variable not detected as not used

南笙酒味 提交于 2019-12-01 16:19:35

问题


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?


回答1:


In theory, the default constructor for std::vector<int> could have arbitrary side effects, so the compiler cannot figure out whether removing the definition of a would change the semantics of the program. You only get those warning for built-in types.

A better example is a lock:

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

Even though a is never used after its definition, removing the first line would be wrong.




回答2:


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.




回答3:


a is actually used after it is declared as its destructor gets called at the end of its scope.



来源:https://stackoverflow.com/questions/4070849/a-variable-not-detected-as-not-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!