Consider the following object:
std::array<std::aligned_storage_t<sizeof(T), alignof(T)>, size> container;
If I have already called placement new on the first element of this array, I believe it is perfectly acceptable to do the following:
reinterpret_cast<T *>(container.data());
This is because data()
returns a pointer to the underlying array, which can also be treated as a pointer to the first element of that underlying array. I have allocated, via placement new, an object at that location, so at that location there is an object of type T
.
Note that reinterpret_cast
should be valid here rather than a static_cast
chain, see static_cast and reinterpret_cast for std::aligned_storage.
However, what if I have not actually called placement new? Is it legal for me to construct this pointer, as long as I do not dereference it?
My motivation here is implementing a std::vector
-like class backed by an static array (so no indirection or dynamic allocation). I am trying to implement the data()
member function. It is convenient to be able to have an always-valid, zero-overhead way of creating a pointers + size pair that represent the data: data()
, size()
. Since size()
would return 0, I end up constructing a pointer that I never dereference.