Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::byte well defined?

Tags:

c++

c++17

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?

like image 705
StoryTeller - Unslander Monica Avatar asked Jul 17 '17 05:07

StoryTeller - Unslander Monica


1 Answers

Essentially there is special wording all around the c++17 draft standard that gives std::byte the same properties with regard to aliasing as char and unsigned char.

To give you an example, in $6.10 in n4659 it states

8 If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined.
[...]
(8.8) — a char, unsigned char, or std::byte type.

I didn't do an exhaustive search, but essentially anywhere that char gets special treatment in the standard, the same is given to std::byte. As far as accessing memory is concerned, it seems irrelevant that it is defined as an enum or what it's underlying type is.

EDIT
Maybe I understood your question wrongly: If you are asking, if the standard guarantees that sizeof(std::byte) == alignof(std::byte) == 1 then I believe this is not the case, as there seems to be no wording about how those properties depend on the underlying type of a scoped enum and I couldn't find special wording for std::byte in that regard. As @T.C. mentions in the comments, this is probably a defect in the language.

like image 108
MikeMB Avatar answered Sep 17 '22 18:09

MikeMB