how do you delete an object allocated with placement new

c++, dynamic-memory-allocation, memory-management, new-operator

Solution

In the first case, there's no point in using placement new, since `int` doesn't have a constructor.

In the second case, it's either pointless (if `myClass` is trivial) or wrong, since there are already objects in the array.

You use placement new to initialise an object in a block of memory, which must be suitably aligned, and mustn't already contain a (non-trivial) object.

char memory[enough_bytes];  // WARNING: may not be properly aligned.
myClass * c = new (memory) myClass;

Once you've finished with it, you need to destroy the object by calling its destructor:

c->~myClass();

This separates the object's lifetime from that of its memory. You might also have to release the memory at some point, depending on how you allocated it; in this case, it's an automatic array, so it's automatically released when it goes out of scope.

Problem

there are quite a few faces for the new operator in c++, but I'm interested in placement new. Suppose you allocate memory at a specific memory location ``` int memoryPool[poolSize*sizeof(int)]; int* p = new (mem) int; //allocates memory inside the memoryPool buffer delete p; //segmentation fault ``` How can I correctly deallocate memory in this case? What if instead of built-in type int I would use some class called myClass? ``` myClass memoryPool[poolSize*sizeof(myClass )]; myClass * p = new (mem) myClass ; //allocates memory inside the memoryPool buffer delete p; //segmentation fault ``` Thanks for your help.

Original source