How to delete object constructed via placement new operator?

前端 未结 4 2150
谎友^
谎友^ 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:00

    Call the destructor

    T * t = (T *)buf;
    t->~T();
    

    then free memory with delete[] buf. Calling destructors explicitly is exactly how it is done for objects created with placement new.

提交回复
热议问题