我有一小段 C++ 代码:
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
int main() {
int i=0;
istream_iterator<string> EOS;
double x;
return 0;
}
现在我用我的 g++ (GCC) 4.4.4 编译它
g++ -W -Wall -pedantic test.cc -o test
得到:
test.cc: In function 'int main()':
test.cc:9: warning: unused variable 'i'
test.cc:11: warning: unused variable 'x'
为什么未使用的 EOS 没有警告?
最佳答案
它不是原始值,因此它的构造函数和/或析构函数可能具有预期的副作用。
为了说明这在实践中发生:我使用一个类来对代码段进行计时,大致如下:
class Timed {
double start;
public:
Timed() { start = now(); }
~Timed() { std::cout << (now() - start) << '\n'; }
}
所以要衡量一个函数需要多长时间,我只是这样做:
void slow() {
Timed t;
// heavy operation here...
}
变量 t
永远不会被使用,但它对代码的行为仍然很重要。
关于c++ - g++ 不显示 'unused' 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5302848/