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

If I have a template class A that contains a pointer, and A has an implicit conversion operator that will return that pointer, do I need or should I define the delete operator for A if I intend to apply delete to objects of this class?

+4
source share
4 answers

I believe that you have something like the following:

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

You intend to "apply delete to objects of this class", so I assume that you mean:

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

If so, then the call to delete correctly destroys the object and frees the memory allocated with the β€œnew” in the previous line, and the answer to your question is β€œno”.

Since you pointed the conversion operator to a pointer, you can use delete for an object of type A<int> (unlike A<int>* ). Using delete will be applied to the result of calling the conversion operator:

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

Basics of working with deletion:

The delete p expression does two different things. First, it calls the destructor for the object pointed to by p , and then frees memory. If you define the operator delete member for your class, then this will be the function that delete p will use to free memory.

In general, you define only those operators when you want to control how to allocate or free memory for dynamic objects of this class.

+2
source

You only need to define the delete operator if you define the new operator - in which case you should pretty much do it.

This does not mean that you will not need to delete A * s, but you do not need to define any operators for this, it will work by default.

+5
source

If your class owns this pointer, it must remove it in its destructor. Keep in mind that overloading this statement can be confusing, since the usual approach to getting a pointer to an object is its address.

+2
source

Does class A need to define an implicit conversion operator? Maybe there is a simple method T* get() const , which returns a pointer, for example, boost and std smart pointer. Implicit conversion can cause all kinds of problems.

0
source

Source: https://habr.com/ru/post/1345917/


All Articles