简体   繁体   English

为什么编译器允许缩小转换

[英]Why compiler allows narrowing conversions

Can anyone please explain to me, why the compiler allows initialize variables of built-in type if the initializer might lead to the loss of information? 任何人都可以向我解释一下,如果初始化器可能导致信息丢失,为什么编译器允许初始化内置类型的变量?

For example C++ Primer, the 5th edition says, that The compiler will not let us list initialize variables of built-in type if the initializer might lead to the loss of information. 例如C ++ Primer,第5版说,如果初始化器可能导致信息丢失,编译器将不会让我们列出内置类型的初始化变量。

but my compiler gcc v 4.7.1 initialized variable a in the following code successfully: 但是我的编译器gcc v 4.7.1在以下代码中成功初始化了变量a

long double ld = 3.1415926536; 
int a{ld};

there was just warning: narrowing conversion of 'ld' from 'long double' to 'int' inside { } [-Wnarrowing]. 只有警告:缩小'ld'从'long double'到'int'的转换{} [-Wararrowing]。

One of the features of initializer lists is that narrowing conversions are not allowed. 初始化列表的一个功能是不允许缩小转换。 But the language definition doesn't distinguish between warnings and errors; 但语言定义不区分警告和错误; when code is ill-formed it requires "a diagnostic", which is defined as any message from a set of implementation-defined messages. 当代码格式错误时,它需要“诊断”,它被定义为来自一组实现定义的消息的任何消息。 Warnings satisfy this requirements. 警告满足此要求。 That's the mechanism for non-standard extensions: having issued a warning, the compiler is free to do anything it wants to, including compiling something according to implementation-specific rules. 这是非标准扩展的机制:发出警告后,编译器可以自由地做任何想做的事情,包括根据特定于实现的规则编译。

You can set the compiler flag to flag all warnings as error. 您可以设置编译器标志以将所有警告标记为错误。 In that case only it will stop you from doing like that. 在这种情况下,只会阻止你这样做。 Otherwise it will only be a warning. 否则它只会是一个警告。

This issue has been coming up lately. 这个问题最近出现了。 With gcc-4.7 a command line switch turns on the required behaviour: 使用gcc-4.7,命令行开关将打开所需的行为:

g++ -Werror=narrowing ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM