I have a question regarding placement new syntax in C++. Are the following two code snippets functionally equivalent and can be used interchangeably (I am not implying that the second should be used, when the first one is suitable)?
#1
T* myObj = new T();
// Do something with myObj
delete myObj;
#2
char* mem = new char[sizeof(T)];
T* myObj = new (mem) T();
// Do something with myObj
myObj->~T();
delete[] mem;
Is there something I should be especially careful of, when I am using the placement new syntax like this?
They are not equivalent, because they have different behaviour if the constructor or the destructor of
Tthrows.new T()will free any memory that has been allocated before letting the exception propagate any further.char* mem = new char[sizeof(T)]; T* myObj = new (mem) T();will not (and unless you explicitly do something to ensure that it gets freed you will have a leak). Similarly,delete myObjwill always deallocate memory, regardless of whether~T()throws.An exact equivalent for
T* myObj = new T();/*other code*/delete myObj;would be something like: