g++ 不显示“未使用"警告

2022-01-23 00:00:00 g++ c++

我有一小段 C++ 代码:

I have a little piece of code in 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 编译它

Now i compile it with my 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 没有警告?

Why there is no warning for unused EOS?

推荐答案

它不是原始值,因此它的构造函数和/或析构函数可能会产生预期的副作用.

It is not a primitive value, so its constructor and/or destructor might have desired side effects.

为了说明这在实践中发生:我使用一个类来对代码段进行计时,大致如下:

To illustrate that this happens in practice: I use a class to time sections of code, that looks roughly like this:

class Timed {
    double start;
    public:
        Timed() { start = now(); }
        ~Timed() { std::cout << (now() - start) << '
'; }
}

所以要衡量一个函数需要多长时间,我只是这样做:

So to measure how long a function takes, I simply do:

void slow() {
    Timed t;
    // heavy operation here...
}

变量 t 永远不会被使用,但它对代码的行为仍然很重要.

The variable t never gets used, but it's still important to the behaviour of the code.

相关文章