c++ - C++ 中的枚举类型是跨平台的吗?

标签 c++ qt serialization enums cross-platform

<分区>

Possible Duplicate:
what is the size of an enum type data in C++?

enum 数据类型是如何在内部存储的(我想象为 8/16/32 位 int?),它可以安全地序列化还是我应该使用 quint8 之类的东西来存储值?换句话说,sizeof(MyEnum) 是否保证在所有平台上都具有相同的大小?

最佳答案

In other words is sizeof(MyEnum) guaranteed to be the same size on all platforms?

您可以在 C++11 中设置显式类型(但在早期的 C++ 版本中不能):

enum class Drug : char {
    Cocaine,
    Cannabis,
    Crack
};

enum Sex : uint32_t {
    Male,
    Female,
    Other
};

enum 前面使用 class 会强制 Drug 的用户将其拼写为 Drug::Cocaine,对于声明前面没有 class 的枚举,拼写是可选的(Sex::MaleFemale 都有效)。

2011 年之前的 C++es 黑客攻击包括以下内容,它们强制最小化:

enum Frob {
    ...
    FORCE_DWORD          = 0x7fffffff
};

在实践中看到,例如在 ReactOS 上 DirectX-SDK implementation .


标准引用

7.2 Enumeration Declarations [dcl.enum]

[...]

§6: For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration. If no integral type can represent all the enumerator values, the enumeration is ill-formed. It is implementation-defined which integral type is used as the underlying type except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0.

关于c++ - C++ 中的枚举类型是跨平台的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13992897/

相关文章:

c++ - 在 Qt 中处理多个窗口

c++ - QGraphicsItem 中的 itemChanged() 用于许多不同的项目

java - Spring 启动2.2.2 : Jackson serializer for custom pagination doesn't work

c++ - Cmake:如何将库标记为依赖于系统库

c++ - 如何使用 Boost.Variant 迭代一系列有界类型

c++ - CMake MacOS X bundle with BundleUtiliies for Qt application

asp.net-mvc-3 - Entity Framework POCO 序列化

c# - Protobuf-net Serializing Parent Class inherited object property 标记为 [ProtoIgnore()] throwing "No serializer defined for type: System.Object"

c++ - 排列 +ve 和 -ve 数字的数组,顺序不变

c++ - 为什么在 mfc 的 listcontrol 中插入的文本显示截断文本? listcontrol 是重新调整大小?