Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 class?

like image 367
user2023370 Avatar asked Jan 21 '23 03:01

user2023370


2 Answers

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.

like image 137
Ernest Friedman-Hill Avatar answered Jan 23 '23 23:01

Ernest Friedman-Hill


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.

like image 35
Richard Corden Avatar answered Jan 24 '23 00:01

Richard Corden