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?
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With