How to delete object constructed via placement new operator?

前端 未结 4 2125
谎友^
谎友^ 2020-12-09 09:38
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 vi         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 10:10

    The memory was actually allocated using char*; which you are properly freeing using delete[] buf. You just need to call the destructor t->~T() in this case for t. No need to delete t;.

    Placement new in this case, is used only to construct the object not for the memory allocation.

提交回复
热议问题