如何删除通过placement new操作符构造的对象? [英] How to delete object constructed via placement new operator?

查看:103
本文介绍了如何删除通过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

So what is correct way to destruct t?

PS上面的代码仅用于描述我的问题,并且与我将要写的代码没有真正的关系。所以请不要给出答案(为什么使用展示位置新的而不是非展示位置?或类似的东西)

P.S. The code above is only for describing my problem, and have not real relationship with code I'm going to write. So please don't give answers like (Why use placement new instead of non-placement? or something similar)

推荐答案

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

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

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

C ++标准:5.4.2

C++ standard: 5.4.2


5.2.4 伪析构函数调用[expr.pseudo]

5.2.4 Pseudo destructor call [expr.pseudo]

1在一个点之后使用
伪析构函数名。或arrow - > operator表示
由type-name命名的非类类型的析构函数。结果
只能用作函数调用operator(),
的操作数,并且这种调用的结果类型为void。唯一的效果是在点或箭头之前的后缀表达式的
求值。
2点运算符的
左侧应是标量类型。箭头操作符的左
手边应该是指向标量类型的指针。
此标量类型是对象类型。由
伪结构体名称指定的类型应与对象类型相同。
此外,
的伪析构名中的两个类型名称形式 :: opt nested-name-specifieropt type-name ::〜type-name shall
指定相同的标量类型。
对象类型和伪析构函数名
指定的类型的cv非限定版本应该是相同的类型。

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 postfixexpression 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 pseudodestructor- 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.

这篇关于如何删除通过placement new操作符构造的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆