You must only call delete
on pointers that were created with operator new
. If you use placement new
with a memory location that was allocated by the normal operator new
then you may safely use delete
on it (provided you get the types and pointers right). However, you can use placement new
on any memory, so you usually will manage that memory some other way and call the object's destructor manually.
For instance, in this convoluted and usually unnecessary scenario, it is safe to delete
the memory you used placement new
on, but only because you allocated it with new
before:
char* mem = new char[sizeof(MyObject)];
MyObject* o = new (mem) MyObject;
// use o
o->~MyObject(); // with placement new you have to call the destructor by yourself
delete[] mem;
However, this is illegal:
char mem[16]; // create a buffer on the stack, assume sizeof(MyObject) == 16
MyObject* o = new (mem) MyObject; // use stack memory to hold a MyObject
// note that after placement new is done, o == mem
// pretend for this example that the point brought up by Martin in the comments didn't matter
delete o; // you just deleted memory in the stack! This is very bad
Another way to think of it is that delete
only deallocates memory allocated previously by the normal new
. With placement new
, you do not have to use memory that was allocated by the normal new
, so with the possibility of not having been allocated by normal new
, delete
cannot deal with it.