开发者

Do I need to overload delete if I have operator T *()?

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 c开发者_JAVA百科lass?


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.


I believe that you've got something like the following:

template <typename T>
struct A {
  T * t;
  operator T* () { return t; } 
};

An you intend to "apply delete to objects of this class", so by that I'm assuming you mean:

void foo ()
{
  A<int> * p = new A<int>;
  delete p;     // Applying 'delete'
}

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 type A<int> (a opposed to A<int>*). The use of delete will be applied to the result of calling the conversion operator:

void foo ()
{
  A<int> a;
  a.t = new int;
  delete a;       // Same as: delete a.operator T*()
}

Basics of how delete works:

The expression delete p, does two different things. Firstly, it calls the destructor for the object pointed to by p and then it frees the memory. If you define an operator delete member for your class then it will be that function which will be used by delete 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.


Does you class A really need to define an implicit conversion operator? Maybe have a simple T* get() const method that returns the pointer, like the boost and std smart pointer do. Implicit conversion can cause all kinds of trouble.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜