Let say p
is a pointer into a buffer of bytes, suitably aligned for objects of type T
.
I’d like to build an array of T
objects at p
but I couldn’t find a way to use placement new
for arrays in a correct way. I found (and wrote) several post on the subject and I was left with the impression that it’s not usable (from memory, one reason was that you could not destroy easily the array).
The solution would be to place the object manually (and destroy them in the same way):
// I'm assuming, the underlying storage is large enough to hold N T objects from p
for (std::size_t i = 0;i != N;++i)
{
new(p+i) T{some constructor args};
}
But in this case, is it legal to alias an array on the address of the first object? Can we perform pointer arithmetic on this “fake array”?
Saying it in another way: would it be legal to reinterpret_cast
the pointer to the first object to an plain array of objects (possibly to a std::array<T,M>*
)?:
// is this legal (not UB)?
T *arr = reinterpret_cast<T *>(p);
// or this?
static_assert(sizeof(std::array<T,N>) == N*sizeof(T));
std::array<T,N> *arr = reinterpret_cast<std::array<T,N> *>(p);
Regarding the std::array
version it’s also related to a more complex use case: is aliasing a plain array to an `std::array` not UB
Regarding the plain array pointer, is it the location of a valid array, thus allowing for indexing and pointer arithmetic.
Isn’t there a cleaner, simpler solution to build an array at a given location?
I’d like the appropriate wording from the standard (I think it might relate to implicit lifetime).