Can this potentially cause undefined behaviour?
uint8_t storage[4];
// We assume storage is properly aligned here.
int32_t* intPtr = new((void*)storage) int32_t
The pointer returned by placement new can be just as UB-causing as any other pointer when aliasing considerations are brought into it. It's your responsibility to ensure that the memory you placed the object into isn't aliased by anything it shouldn't be.
In this case, you cannot assume that uint8_t
is an alias for char
and therefore has the special aliasing rules applied. In addition, it would be fairly pointless to use an array of uint8_t
rather than char
because sizeof()
is in terms of char
, not uint8_t
. You'd have to compute the size yourself.
In addition, reinterpret_cast
's effect is entirely implementation-defined, so the code certainly does not have a well-defined meaning.
To implement low-level unpleasant memory hacks, the original memory needs to be only aliased by char*
, void*
, and T*
, where T
is the final destination type- in this case int
, plus whatever else you can get from a T*
, such as if T
is a derived class and you convert that derived class pointer to a pointer to base. Anything else violates strict aliasing and hello nasal demons.