gpt4 book ai didi

c++ - Clang (3.6.0) 忽略包含头文件的警告

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

似乎 clang 忽略了包含的头文件中出现的警告:

// what.hpp
class What {
public:
What() {
int x = x;
}
};

// main.cpp
#include <iostream>
#include "what.hpp"
int main()
{
int y = y;
std::cout << "y is: " << y << std::endl;
What w;
}

用 g++ (4.9.2) 编译得到:

$ g++ -dumpversion && g++ -Wall -Wextra main.cpp -o main
4.9.2
In file included from main.cpp:3:0:
what.hpp: In constructor ‘What::What()’:
what.hpp:5:17: warning: ‘x’ is used uninitialized in this function [-Wuninitialized]
int x = x;
^
main.cpp: In function ‘int main()’:
main.cpp:5:13: warning: ‘y’ is used uninitialized in this function [-Wuninitialized]
int y = y;

用 clang 编译同样的东西:

$ clang++ --version && clang++ -Wall -Wextra main.cpp -o main
Ubuntu clang version 3.6.0-2ubuntu1~trusty1 (tags/RELEASE_360/final) (based on LLVM 3.6.0)
Target: x86_64-pc-linux-gnu
Thread model: posix
main.cpp:5:13: warning: variable 'y' is uninitialized when used within its own initialization [-Wuninitialized]
int y = y;
~ ^
1 warning generated.

我不确定,如果我使用的 clang 有误,或者这确实是一个错误?有什么提示吗?提前致谢。

最佳答案

这不是 clang 错误,警告被抑制是因为 x 随后未被使用,我在下面引用的错误报告解释了此行为背后的基本原理。

在这种特定情况下,如果变量未被使用,它被认为是 clang 特性 不产生此警告(Wuninitialized),尽管大多数人可能会发现这令人惊讶行为。

我们可以从以下错误报告中看出原因:No uninitialized warning for self-initialization (e.g., int x = x) :

Right, this is deliberate, and is considered to be a feature rather than a bug. We suppress the warning on 'int x = x;' only in the case where 'x' is otherwise unused.

bug报告中提到,这种方式的自初始化是:

considered the canonical way to suppress "use of uninitialized variable" warnings

这不取决于所讨论的代码是否包含在 header 中,我将 live example 放在一起当代码全部在一个文件中时,显示警告不会出现。

注意,以这种方式初始化一个变量:

int x = x;

是未定义的行为,引用见:

所以一般来说,我们不能对结果有任何期望,编译器也没有义务发出诊断,尽管这样做可能会有帮助。

关于c++ - Clang (3.6.0) 忽略包含头文件的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30959510/

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