This is a follow up to this other question about memory re-use. As the original question was about a specific implementation, the answer was related to that specific implementat
Passer By's answer covers why the example program has undefined behaviour. I'll attempt to answer how to reuse storage without UB with minimal UB (reuse of storage for arrays is technically impossible in standard C++ given the current wording of the standard, so to achieve reuse, the programmer has to rely on the implementation to "do the right thing").
Converting a pointer does not automatically manifest objects into being. You have to first construct the float objects. This starts their lifetime and ends the lifetime of the int objects (for non-trivial objects, destructor would need to be called first):
for(int i=0; i
You can use the pointer returned by placement new (which is discarded in my example) directly to use the freshly constructed float
objects, or you can std::launder
the buffer
pointer:
float *out = std::launder(reinterpret_cast(buffer));
However, it is much more typical to reuse the storage of type unsigned char
(or std::byte
) rather than storage of int
objects.