gpt4 book ai didi

c++ - 与 C++11 `enum class` 的 ABI 兼容性保留

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:04:19 24 4
gpt4 key购买 nike

这与 Does adding enumerators into enum break ABI? 几乎是同一个问题,但使用 C++11 引入的 enum class

据我了解 this page我可以通过为我的枚举定义一个底层类型来简单地拥有一个稳定的 ABI:

enum class Foo : uint32_t
{
x, y, z
}

我会说这很好用,例如

enum class Foo : uint8_t { x = 257 }

不会编译。这意味着编译器不再默默地更改我的枚举的大小,因此我最终不会破坏二进制兼容性。

我说的对吗?

最佳答案

我相信the accepted answer to the referenced question回答了大多数关于 ABI 兼容性的问题。我可以在这里重复一遍,但我看不出那里有多大值(value)。

为了解决您关于 C++11 作用域枚举的具体问题,您的示例:

enum class Foo : uint8_t { x = 257 }

格式错误,因为它需要缩小转换,需要实现来提供诊断,但如果实现仅使其发出警告,则它可能会编译。如您所问,编译器不会默默地更改基础类型的大小。

我们可以从 C++ 标准草案 dcl.enump5 中看出这一点:

Each enumeration defines a type that is different from all other types. Each enumeration also has an underlying type. The underlying type can be explicitly specified using an enum-base. For a scoped enumeration type, the underlying type is int if it is not explicitly specified. In both of these cases, the underlying type is said to be fixed. Following the closing brace of an enum-specifier, each enumerator has the type of its enumeration. If the underlying type is fixed, the type of each enumerator prior to the closing brace is the underlying type and the constant-expression in the enumerator-definition shall be a converted constant expression of the underlying type. If the underlying type is not fixed, the type of each enumerator prior to the closing brace is determined as follows: ...

converted constant expression禁止收缩转换,来自expr.constp5 :

A converted constant expression of type T is an expression, implicitly converted to type T, where the converted expression is a constant expression and the implicit conversion sequence contains only

...

  • integral conversions other than narrowing conversions,

...

关于c++ - 与 C++11 `enum class` 的 ABI 兼容性保留,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53381626/

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