gpt4 book ai didi

c++ - 编译器在使用列表初始化时不会报错会导致信息丢失

转载 作者:行者123 更新时间:2023-11-30 02:53:54 25 4
gpt4 key购买 nike

在c++ primer(5th)中提到:

When used with variables of built-in type, this form of initialization has one important property: The compiler will not let us list initialize variables of built-in type if the initializer might lead to the loss of information:

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};

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

最佳答案

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

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

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

也有一个命令行选项:-Werror=narrowing,但是既然你想根据 GCC 改变程序本身的语义,把它放在源代码中可能更合适的。

请注意,除了简单的良构性之外,当它产生差异时,例如在过载选择中,GCC 会正确诊断条件。

关于c++ - 编译器在使用列表初始化时不会报错会导致信息丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17560389/

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