gpt4 book ai didi

c++ - g++ 不显示 'unused' 警告

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:20:59 25 4
gpt4 key购买 nike

我有一小段 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/49979956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com