如何删除通过放置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
的正确方法是什么?
PS上面的代码仅用于描述我的问题,与我要编写的代码没有真正的关系。所以请不要给出类似的答案(为什么使用placement new
而不是non-placement?或类似的东西)
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;
So what is correct way to destruct t
?
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
错误。即使
T
可以是原始类型,该代码在模板代码中也是合法且正确的。C++ 标准:5.4.2
Wrong. That code is legal and correct in template code even if
T
can be a primitive type.C++ standard: 5.4.2
首先通过直接调用析构函数来析构对象:
然后通过对从
new[]
返回的指针调用delete[]
来销毁内存:You first destruct the object by directly calling the destructor:
Then you destroy the memory by calling
delete[]
on the pointer returned fromnew[]
:调用析构函数
,然后使用
delete[] buf
释放内存。显式调用析构函数正是使用放置new
创建的对象的做法。Call the destructor
then free memory with
delete[] buf
. Calling destructors explicitly is exactly how it is done for objects created with placementnew
.内存实际上是使用
char*
分配的; 您正在使用delete[] buf
正确释放它。在本例中,您只需为t
调用析构函数t->~T()
即可。无需删除 t;
。Placement
new
在这种情况下,仅用于构造对象,而不用于内存分配。The memory was actually allocated using
char*
; which you are properly freeing usingdelete[] buf
. You just need to call the destructort->~T()
in this case fort
. No need todelete t;
.Placement
new
in this case, is used only to construct the object not for the memory allocation.