这个表达式可以在标准(N3797)的 §8.5.4/7 的例子中找到
unsigned int ui1 = {-1}; // error: narrows
鉴于 §8.5.4/7 及其第 4 个要点:
A narrowing conversion is an implicit conversion:
- from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.
我会说这里没有收缩,因为 -1 是一个常量表达式,其整数提升后的值适合一个无符号整数。
另见§4.5/1 关于积分促销:
A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.
从 4.13 开始,我们知道 -1(int)的秩等于 unsigned int 的秩,因此它可以转换为 unsigned int。
编辑
不幸的是Jerry Coffin从此线程中删除了他的答案。我相信他走在正确的轨道上,如果我们接受 §8.5.4/7 中第 4 个要点的当前阅读是错误的事实,在此之后 change在标准中。
最佳答案
没有从int
到unsigned int
的整数提升,因此它仍然是错误的。
那将是一个整体转换。
关于c++ - 为什么下面的表达式表征缩小转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21242070/