使用列表初始化时,编译器不会给出错误,这会导致信息丢失 [英] Compiler does not give error when using list initialization which will cause information loss

查看:51
本文介绍了使用列表初始化时,编译器不会给出错误,这会导致信息丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c ++入门(第5版)中,它提到:

In c++ primer(5th), it mentioned:


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

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编译代码,它只会给出警告而不是错误。

I compile the code using gcc4.8.1 , it only give a warning rather than an error.

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

是否有任何标记会打开重要属性的功能?

Is there any flags that will turn on the feature of the important property ?

推荐答案

快速搜索 gcc诊断标志会占用文档资源。

A quick search for "gcc diagnostic flag" turns up documentation resources.

在程序内部,您可以执行以下操作:

Inside your program, you could do this:

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

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

There is a command-line option too: -Werror=narrowing, but since you want to alter the semantic meaning of the program itself according to GCC, putting it in the source code is probably more appropriate.

请注意,当它除了简单的良好格式(例如在选择重载方面)有所不同时,GCC会正确诊断该情况。

Note, when it makes a difference other than simple well-formedness, such as in overload selection, GCC does diagnose the condition correctly.

这篇关于使用列表初始化时,编译器不会给出错误,这会导致信息丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆