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
的正确方法?
附:上面的代码只是为了描述我的问题,和我要写的代码没有真正的关系。所以请不要给出类似的答案(为什么使用placement new
而不是non-placement?或类似的东西)
最佳答案
...instantiated via basic types as well (say
int
) so such codet->~T();
is incorrect...
错了。即使 T
可以是原始类型,该代码在模板代码中也是合法且正确的。
C++ 标准:5.4.2
5.2.4 Pseudo destructor call [expr.pseudo]
- The use of a pseudo-destructor-name after a dot
.
or arrow->
operator represents the destructor for the non-class type named by type-name. The result shall only be used as the operand for the function calloperator ()
, and the result of such a call has type void. The only effect is the evaluation of the postfix expression before the dot or arrow.- The left hand side of the dot operator shall be of scalar type. The left hand side of the arrow operator shall be of pointer to scalar type. This scalar type is the object type. The type designated by the pseudo destructor- name shall be the same as the object type. Furthermore, the two type-names in a pseudodestructor- name of the form
::opt nested-name-specifieropt type-name :: ˜ type-name
shall designate the same scalar type. The cv-unqualified versions of the object type and of the type designated by the pseudo-destructor-name shall be the same type.
关于c++ - 如何删除通过放置新运算符构造的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6730403/