gpt4 book ai didi

c++ - 值初始化枚举的行为

转载 作者:IT老高 更新时间:2023-10-28 12:37:55 28 4
gpt4 key购买 nike

首先,我想说,根据 cppreference.com,对枚举进行值初始化有点不可能。

根据http://en.cppreference.com/w/cpp/language/value_initialization ,值初始化枚举实际上执行零初始化。然后,根据 http://en.cppreference.com/w/cpp/language/zero_initialization ,对枚举进行零初始化的效果是:

If T is a scalar type, the object's initial value is the integral constant zero implicitly converted to T.

但是,整数常数零不能隐式转换为枚举。最终,枚举不能进行值初始化。这听起来很奇怪,并且值初始化枚举确实适用于 VC、GCC 和 clang。那么,标准对此有何规定?

第二,根据http://en.cppreference.com/w/cpp/language/static_cast :

Integer, floating-point, or enumeration type can be converted to any complete enumeration type (the result is unspecified (until C++17) undefined behavior (since C++17) if the value of expression, converted to the enumeration's underlying type, is not one of the target enumeration values)

那么,如果目标枚举没有等于 0 的枚举数,这是否意味着对枚举进行值初始化(如果它确实有效)实际上可能会导致未定义的行为?

最佳答案

评论中给出了答案。下面给出了我试图解释其背后的整个标准的尝试。

To zero-initialize an object or reference of type T means:

  • if T is a scalar type (3.9), the object is initialized to the value obtained by converting the integer literal 0 (zero) to T;

(枚举是标量类型;§3.9/9)因此,由于转换不是隐式的,我们不是在看第 4 节,而是在第 5.2.9 节;

The result of the expression static_cast<T>(v) is the result of converting the expression v to type T.

§5.2.9/10 然后定义如何将整数值转换为枚举类型。

A value of integral or enumeration type can be explicitly converted to an enumeration type. The value is unchanged if the original value is within the range of the enumeration values (7.2). Otherwise, the resulting value is unspecified (and might not be in that range).

必须证明零在所有枚举的枚举值范围内。
接下来的五个引述取自第 7.2/8 节:

For an enumeration whose underlying type is fixed, the values of the enumeration are the values of the underlying type.

由于所有允许的基础类型在其值范围内都包含零*,因此这会自动给出所需的结果。现在,对于没有固定基础类型的枚举,

Otherwise, for an enumeration where emin is the smallest enumerator and e max is the largest, the values of the enumeration are the values in the range b min to b max , defined as follows:

即我们必须证明 bmin 总是小于或等于零,而 bmax 总是大于或等于零。

Let K be 1 for a two’s complement representation and 0 for a one’s complement or sign-magnitude representation.
b max is the smallest value greater than or equal to max(|e min| − K, |e max|) and equal to 2M − 1, where M is a non-negative integer.

|e max| 是非负数,两个数的最大值至少与两个数一样大。因此 max(|e min| - K, |e max|) 也是非负的,并且 bmax 必须大于或等于该数字 - 所以我们的第一个要求得到满足。

b min is zero if emin is non-negative and −(bmax + K) otherwise.

bmin 显然是零或负数:bmax 是非负数,如上所示,并且 K 是非负的(0 或 1),因此它们和的加法逆是非正的。我们的第二个要求得到满足。最后,

If the enumerator-list is empty, the values of the enumeration are as if the enumeration had a single enumerator with value 0.

这通过设置 emin = emax = 0 得到上述结果。


  • 这简化为“所有整数类型在其值范围内都为零”的说法,这留给读者来证明。

关于c++ - 值初始化枚举的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27935026/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com