C++ 标准是否指定在某些情况下编译应该失败并出现错误?

2022-01-12 00:00:00 type-conversion language-lawyer c++ iso

我正在检查有关缩小转换的标准,我认为对于缩小转换应该触发一个错误.因为 标准 说:

I'm checking the standard about narrowing conversion, and I think for a narrowing conversion an error should be triggered. Because the standard says:

[ 注意:如上所述,列表初始化中的顶层不允许进行此类转换.――尾注]

[ Note: As indicated above, such conversions are not allowed at the top level in list-initializations. ― end note ]

我认为不允许"的描述意味着编译应该失败.

I think the description of "not allowed" means the compiling should fail.

但是有人告诉我,这里只是说程序格式错误",并且标准不会要求编译必须失败.

But someone told me that here just says "the program is ill-formed", and the standard won't require that compilation must fail.

如果需要缩小转换(见下文)来转换元素到 T,程序是非良构的.

if a narrowing conversion (see below) is required to convert the element to T, the program is ill-formed.

所以我的问题是:标准是否指定是否应生成错误或警告?或者在某些情况下编译应该失败?从编译器的角度来看,让程序编译并给出一些警告是否可以?

So my question is: Does the standard specify whether an error or warning should be generated? Or for some cases the compiling should fail? From the aspect of a compiler, is it OK to make the program compile and just give some warnings?

顺便说一句:Clang 4.0.0 和 Gcc 7.0.0 行为不同.

BTW: Clang 4.0.0 and Gcc 7.0.0 behave differently.

float a {1.e39}; // Error for both Clang and GCC
double d;
float a3{d};     // Error for Clang, warning for GCC

推荐答案

标准没有使用术语错误"和警告",它只讨论编译器必须发出诊断"的情况.

The standard doesn't use the terms "error" and "warning", it only talks about cases where the compiler must "issue a diagnostic".

在您的示例中,如果程序格式错误",编译器需要以某种方式告诉您 - 发出诊断.

In your example, if the program is "ill-formed", the compiler is required to tell you that somehow - issue a diagnostic.

之后,它可以做任何它喜欢的事情――包括编译和运行程序.该标准仅指定符合代码的情况,其他所有内容均未定义.然后,正如我们所知,任何事情都可能发生.

After that, it can do anything it likes - including compiling and running the program anyway. The standard only specifies what happens for conforming code, everything else is undefined. And then, as we know, anything can happen.

相关文章