c++ - 如何删除通过放置新运算符构造的对象?

标签 c++ templates new-operator destructor placement-new

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 code
t->~T(); is incorrect
...

错了。即使 T 可以是原始类型,该代码在模板代码中也是合法且正确的。

C++ 标准:5.4.2

5.2.4 Pseudo destructor call [expr.pseudo]

  1. 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 call operator (), 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.
  2. 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/

相关文章:

C++:递归分配内存?

c++ - 如何找出 cpp 中的字符串中是否有 std::vector?

c++ - 在循环中将相同的 unique_ptr 移动到函数中

c++ - MongoDB c++ 遗留驱动程序 1.1.2 不工作 - 使用 VS2013、Win 10、boost-1_62 编译

c++ - googletest 中的参数化和共享资源测试

c++ - 查找动态分配数组的大小

C++ 模板在参数中指定类型

c++ - 模板访问器无法从 T 转换为 T& (C++)

c++ - 成员变量如何与专门的类模板一起使用?

c++ - 放置新和删除