Global “placement” delete[]

后端 未结 4 1745
北恋
北恋 2021-02-06 03:19

I am trying to replace new/delete with my own allocator(s). So, overriding placement new and delete - quite happy with that. Looks something like this ...

void*          


        
4条回答
  •  不要未来只要你来
    2021-02-06 03:44

    There is no such terminology as "placement delete". As you said, if you allocate something with placement new, then when it comes time to deallocate you need to manually invoke the destructor and then also take care of the actual memory buffer allocated for placement new.

    But what you're trying to do is not possible without manually keeping track of your own allocation sizes. The reason is that the whole point of "placement new" is to decouple allocation from object initialization. So with placement new, the act of allocating a memory buffer is totally separate from constructing or destructing whatever objects may (or may not) ever find themselves living in that buffer.

    So, for example, if you allocate some buffer, like char buf[1000], and then you use placement new to construct an array of Foo objects in that buffer, where is C++ supposed to store the array size information? It's not going to store it in your buffer, because it doesn't know what you want to do with that buffer. So it's up to you to record the size of each allocation, and then properly couple that with deallocation.

提交回复
热议问题