【发布时间】:2011-10-07 12:11:03
【问题描述】:
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;
那么破坏t的正确方法是什么?
附:上面的代码只是为了描述我的问题,和我要写的代码没有真正的关系。所以请不要给出类似的答案(为什么使用安置new 而不是非安置?或类似的东西)
【问题讨论】:
-
您应该使用
T *t = new (buf) T:而不是T *t = (T*)buf;。这使您可以避免看起来可疑的演员表(所有演员表都是可疑的,但特别是这个,因为在大多数情况下,从char*转换为T*将违反别名。)
标签: c++ templates new-operator destructor placement-new