How to delete object constructed via placement new operator?

我的未来我决定 提交于 2019-11-28 08:19:39
Armen Tsirunyan

...instantiated via basic types as well (say int) so such code
t->~T(); is incorrect
...

Wrong. That code is legal and correct in template code even if T can be a primitive type.

C++ standard: 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.
Nicol Bolas

You first destruct the object by directly calling the destructor:

t->~T();

Then you destroy the memory by calling delete[] on the pointer returned from new[]:

delete []buf;

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!