阅读 C++17 草案 §6.9.1/5:
Types
char16_t
andchar32_t
denote distinct types with the same size, signedness, and alignment asuint_least16_t
anduint_least32_t
, respectively, in<cstdint>
, called the underlying types.
现在引用C11 draft §7.20.1.2/2,这是C库继承的引用:
The typedef name
uint_leastN_t
designates an unsigned integer type with a width of at least N , such that no unsigned integer type with lesser size has at least the specified width. Thus,uint_least16_t
denotes an unsigned integer type with a width of at least 16 bits.
注意“至少”部分。这意味着 char16_t
实际上可能有例如32 位,构成 char16_t
的数组UTF-16 原始数据的错误表示。在这种情况下,将这样的数组写入二进制文件将导致有效代码单元与 U+0000 个字符交替出现。
char16_t
有充分的理由吗?根据 uint_least16_t
定义而不是 uint16_t
?还是仅仅是标准的缺陷?
最佳答案
首先,顾名思义,uint_least16_t
需要是可以容纳 16 位的最小大小。在同时具有 16 位和 32 位整数的系统上,它不能是 32 位。
其次,uint16_t
不需要存在。它只存在于具有 16 位整数类型的系统上。诚然,这些很常见,但 C 和 C++ 旨在对它们可以定位的硬件施加最小限制,并且有些系统没有 16 位整数类型。
在具有 16 位整数类型的系统上,uint16_t
将是 16 位宽(duh...),uint_least16_t
也将是 16 位宽的。在没有 16 位整数类型的系统上,uint16_t
将不存在,而 uint_least16_t
将存在。对于需要将值存储在可表示为 16 位的范围内的代码,使用 uint_least16_t
是可移植的。对于需要存储正好 16 位的代码(这种情况很少见),uint16_t
是可行的方法。
关于c++ - 为什么将 char16_t 定义为具有与 uint_least16_t 相同的大小而不是 uint16_t?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50965615/