This example is copied from cppreference.
struct Y { int z; };
alignas(Y) std::byte s[sizeof(Y)];
Y* q = new(&s) Y{2};
const int f = reinterpret_cast<Y*>(&s)->z; // Class member access is undefined
// behavior: reinterpret_cast<Y*>(&s)
// has value "pointer to s" and does
// not point to a Y object
const int g = q->z; // OK
const int h = std::launder(reinterpret_cast<Y*>(&s))->z; // OK
I wonder if adding operations like s[0] = std::byte{0}
after statements above is undefined behavior? It seems that it doesn't disobey strict aliasing rule, for std::byte
can be an "AliasedType" for any type according to cppreference, which means it's legal to view any object as array of bytes.
Notice that I add c++20 label because they may only be well-defined after C++20.
std::byte
is an "AliasedType". – Harkerstd::launder
is needed. – Bleareyeds[0] = std::byte{0}
after statements above is undefined behavior? You mean afternew(&s) Y{2}
? Yes, it is undefined behavior because it would be an access to an out-of-lifetime object. – Stempien