c++ - 为什么下面的表达式表征缩小转换?

标签 c++ c++11 language-lawyer narrowing

这个表达式可以在标准(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在标准中。

最佳答案

没有从intunsigned int的整数提升,因此它仍然是错误的。

那将是一个整体转换

关于c++ - 为什么下面的表达式表征缩小转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21242070/

相关文章:

c++ - 空类和派生虚拟类的大小

c++ - 将迭代器放在其中的容器上

c++ - 末端指针会与其他对象重叠吗?

c++ - 下一个 block 的偏移量不正确(DEFLATE/PNG)?

c++ - 如何在ffmpeg(c++)中获取视频流的格式

c++ - 为什么这条线无限循环?

c++ - 将模板类型参数作为模板非类型参数的类型传递

c - extern 对于内联函数声明是否重要?

c++ - 我可以在没有自定义析构函数的情况下使用 std::shared_ptr 和 weak_ptr 创建共享对象池吗?

c++ - 在编译时检测 typedef(模板元编程)