如果我有运算符 T *(),我是否需要重载删除?
如果我有一个包含指针的模板类 A
,并且 A
有一个将返回该指针的隐式转换运算符,我是否需要或应该定义一个如果我打算将 delete
应用于此类的对象,请使用 A
的 delete
运算符?
If I have a template class A
which holds a pointer, and A
has an implicit conversion operator which will return that pointer, do I need to, or should I, define a delete
operator for A
, if I intent to apply delete
to objects of this class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果定义operator new,则只需定义operator delete - 在这种情况下,您几乎必须这样做。
这并不意味着某些东西不需要删除您的 A* —— 但您不需要为此定义任何运算符,它会默认工作。
You only need to define operator delete if you define operator new -- in which case you pretty much must do so.
That doesn't mean that something won't need to delete your A*s -- but you don't need to define any operators for that, it will work by default.
我相信您已经得到了类似以下内容:
您打算“将
删除
应用于此类的对象”,因此我假设您的意思是:如果是这种情况,那么对delete的调用正确地销毁了对象并释放了通过在前一行使用“new”分配的内存,并且您的问题的答案是“否”。
因为您已经声明了一个指针转换运算符,所以可以对
A
类型的对象使用delete
(与A相反) ;*
)。delete
的使用将应用于调用转换运算符的结果:delete 工作原理的基本知识:
表达式
delete p
执行以下两个操作:不同的事情。首先,它调用p
指向的对象的析构函数,然后释放内存。如果您为类定义了operator delete
成员,那么delete p
将使用该函数来释放内存。一般来说,只有当您想要控制如何分配或释放该类的动态对象的内存时,才定义这些运算符。
I believe that you've got something like the following:
An you intend to "apply
delete
to objects of this class", so by that I'm assuming you mean:If this is the case, then the call to delete correctly destroys the object and frees the the memory allocated by the use of 'new' on the previous line and the answer to your question is 'no'.
Because you have declared a conversion operator to a pointer, it is possible to use
delete
on an object of typeA<int>
(a opposed toA<int>*
). The use ofdelete
will be applied to the result of calling the conversion operator:Basics of how delete works:
The expression
delete p
, does two different things. Firstly, it calls the destructor for the object pointed to byp
and then it frees the memory. If you define anoperator delete
member for your class then it will be that function which will be used bydelete p
to free the memory.In general, you only define those operators when you want to control how the memory for dynamic objects of that class should be allocated or freed.
如果您的类拥有此指针,则应在其析构函数中将其删除。请注意,重载此运算符可能会令人困惑,因为获取对象指针的常用方法是获取其地址。
If your class owns this pointer, it should delete it in its destructor. Be aware that overloading this operator may be confusing, because the usual approach to obtain a pointer to an object is by taking its address.
您的类
A
真的需要定义隐式转换运算符吗?也许有一个简单的T* get() const
方法来返回指针,就像 boost 和 std 智能指针一样。隐式转换可能会导致各种麻烦。Does you class
A
really need to define an implicit conversion operator? Maybe have a simpleT* get() const
method that returns the pointer, like the boost and std smart pointer do. Implicit conversion can cause all kinds of trouble.