char * buf = new char[sizeof(T)];
new (buf) T;
T * t = (T *)buf;
//code...
//here I should destruct *t but as it is argument of template and can be
//instantiated via basic types as well (say int) so such code
/*t->~T();*/
//is incorrect (maybe correct? Strange, but it works on VS 2005 for basic types.)
//and this code
/*delete t;*/
//crashes the program.
delete [] buf;
So what is correct way to destruct t
?
P.S. The code above is only for describing my problem, and have not real relationship with code I'm going to write. So please don't give answers like (Why use placement new
instead of non-placement? or something similar)
You first destruct the object by directly calling the destructor:
Then you destroy the memory by calling
delete[]
on the pointer returned fromnew[]
:Call the destructor
then free memory with
delete[] buf
. Calling destructors explicitly is exactly how it is done for objects created with placementnew
.The memory was actually allocated using
char*
; which you are properly freeing usingdelete[] buf
. You just need to call the destructort->~T()
in this case fort
. No need todelete t;
.Placement
new
in this case, is used only to construct the object not for the memory allocation.Wrong. That code is legal and correct in template code even if
T
can be a primitive type.C++ standard: 5.4.2