Search code examples
c++c++17std-byte

Is std::byte well defined?


C++17 introduces the std::byte type. A library type that can (supposedly) be used to access raw memory, but stands separate from the character types and represents a mere lump of bits.

So far so good. But the definition has me slightly worried. As given in [cstddef.syn]:

enum class byte : unsigned char {};

I have seen two answers on SO which seem to imply different things about the robustness of the above. This answer argues (without reference) that an enumeration with an underlying type has the same size and alignment requirements as said type. Intuitively this seems correct, since specifying an underlying type allows for opaque enum declarations.

However, this answer argues that the standard only guarantees that two enumerations with the same underlying type are layout compatible, and no more.

When reading [dcl.enum] I couldn't help but notice that indeed, the underlying type is only used to specify the range of the enumerators. There is no mention of size or alignment requirements.

What am I missing?


Solution

  • CWG2590 fixed this oversight; it’s first published in C++23, but is of course meant to apply to all versions since “everyone knows” enum works this way.