Let's consider following piece of code:
struct Blob {
double x, y, z;
} blob;
char* s = reinterpret_cast<char*>(&blob);
s[2] = 'A';
Assuming that sizeof(double) is 8, does this code trigger undefined behaviour?
Let's consider following piece of code:
struct Blob {
double x, y, z;
} blob;
char* s = reinterpret_cast<char*>(&blob);
s[2] = 'A';
Assuming that sizeof(double) is 8, does this code trigger undefined behaviour?
Chapter 3.10 of the standard seems to allow for that specific case, assuming that "access the stored value" means "read or write", which is unclear.
Quoting from N4140 (roughly C++14):
This does, in principle, allow assignment directly to
s[2]
if you take the position that assignment tos[2]
is indirectly required to be equivalent to copying all of some otherBlob
into an array that just happens to be bytewise identical except for the third byte, and copying it into yourBlob
: you're not assigning tos[0]
,s[1]
, etc. For trivially copyable types includingchar
, that is equivalent to setting them to the exact value they already have, which also has no observable effect.However, if the only way to get
s[2] == 'A'
is by memory manipulation, then a valid argument could also be made that what you're copying back into yourBlob
isn't the underlying bytes that made up any previousBlob
. In that case, technically, the behaviour would be undefined by omission.I do strongly suspect, especially given the "whether or not the object holds a valid value of type
T
" comment, that it's intended to be allowed.