gcc warning flags for implicit conversions

。_饼干妹妹 提交于 2019-12-05 14:11:11

问题


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?


回答1:


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() };
                                   ^



回答2:


You can use -Wconversion and avoid error for unsigned - 1 with -Wno-sign-conversion, like specified here.



来源:https://stackoverflow.com/questions/35842477/gcc-warning-flags-for-implicit-conversions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!