1

在 c++ Primer(5th) 中,它提到:

当与内置类型的变量一起使用时,这种形式的初始化有一个 重要的属性:如果初始化器可能导致信息丢失,编译器不会让我们列出内置类型的初始化变量:

longdouble ld = 3.1415926536;
int a{ld}, b = {ld}; // error: narrowing conversion required
int c(ld), d = ld;  // ok: but value will be truncate

我使用 gcc4.8.1 编译代码,它只给出警告而不是错误。

g++  -W -Wall -Wextra -pedantic -std=c++0x  -o m main.cpp


main.cpp: In function ‘int main()’:
main.cpp:64:13: warning: narrowing conversion of ‘ld’ from ‘long double’ to ‘int’ inside { } [-Wnarrowing]
     int a{ld}, b= {ld}; 
             ^
main.cpp:64:22: warning: narrowing conversion of ‘ld’ from ‘long double’ to ‘int’ inside { } [-Wnarrowing]
     int a{ld}, b= {ld}; 

是否有任何标志可以打开重要属性的功能?

4

2 回答 2

2

快速搜索“gcc 诊断标志”可以找到文档资源。

在你的程序中,你可以这样做:

#ifdef __GNUC__
#   pragma GCC diagnostic error "-Wnarrowing"
#endif

还有一个命令行选项:-Werror=narrowing,但是由于您想根据 GCC 更改程序本身的语义,因此将其放在源代码中可能更合适。

请注意,当它除了简单的良构之外产生影响时,例如在重载选择中,GCC 确实可以正确诊断情况。

于 2013-07-10T00:35:15.337 回答
1

该标准从不要求错误或警告:该标准只需要一个实现来发出诊断。这种诊断是采用编译器错误的形式,还是警告的形式,或者完全不同于它们两者的形式,都超出了标准的范围。

于 2013-07-10T00:59:53.010 回答