Is it legal to reuse memory from a fundamental type array for a different (yet still fundamental) type array

前端 未结 3 2060
甜味超标
甜味超标 2021-02-07 11:53

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

3条回答
  •  梦毁少年i
    2021-02-07 12:29

    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.

提交回复
热议问题