隐式转换的gcc警告标志 [英] gcc warning flags for implicit conversions
问题描述
double getSomeValue()
{
返回4.0;
}
...
std :: string str;
str = getSomeValue();
正如您在这里看到的,很容易发现问题,但是在大代码库中 如何强制GCC针对这些危险的隐式转换发出警告?我试过 您可以使用 但是,请注意,使用C ++ 11 统一初始化大括号语法时,您会收到开箱即用的警告,但不包含 getSomeValue()
与调用代码不在同一个文件中,因此可能很难将这个 double
指向 std :: string
静音转换。 GCC使用 -Wall -Wextra -Werror
编译这段代码(这里的示例输出,我不知道使用了什么警告标志:
-Wconversion
,但它非常严格,并且在大多数包含的头文件中导致错误,例如 unsigned - 1
。是否有较弱版本的 -Wconversion
? -Wfloat-conversion
标志或更广泛的 -Wconversion
。
-Wconversion
标志;例如:
#include< string>
double getSomeValue(){
return 4.0;
int main(){
std :: string str {getSomeValue()}; // C ++ 11 brace-init
}
C:\Temp\CppTests> g ++ -std = c ++ 11 test.cpp
test.cpp:在函数'int main()'中:
test.cpp:8:35:warning:缩小'getSomeValue()'从'double'的转换时间t $ b $'char'内部{} [-Wnarrowing]
std :: string str {getSomeValue() };
^
I recently had a bug in a similar context to next one:
double getSomeValue()
{
return 4.0;
}
...
std::string str;
str = getSomeValue();
As you can see here is easy to spot the problem, but in a large code base where getSomeValue()
is not in the same file with the calling code it might be difficult to spot this double
to std::string
silent conversion. GCC compiles this code fine with -Wall -Wextra -Werror
(sample output here, I don't know what warning flags were used: http://ideone.com/BTXBFk).
How may I force GCC to emit warnings for these dangerous implicit conversions? I tried -Wconversion
, but it is very strict and it causes errors in most included headers for common cases like unsigned - 1
. Is there a weaker version of -Wconversion
?
You can use the -Wfloat-conversion
flag, or the broader -Wconversion
.
However, note that with C++11 uniform initialization brace syntax, you get a warning "out of the box", without the -Wconversion
flag; e.g.:
#include <string>
double getSomeValue() {
return 4.0;
}
int main() {
std::string str{ getSomeValue() }; // C++11 brace-init
}
C:\Temp\CppTests>g++ -std=c++11 test.cpp test.cpp: In function 'int main()': test.cpp:8:35: warning: narrowing conversion of 'getSomeValue()' from 'double' t o 'char' inside { } [-Wnarrowing] std::string str{ getSomeValue() }; ^
这篇关于隐式转换的gcc警告标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!