Is it possible to have a virtual delete operator? I'm not talking destructor, I mean the actual operator overload.
Minus the fact that it is (in most cases) a big bad idea to overload new and delete (Yes, I already know it's heresy), I want to know what kind of implications come from using a virtual delete operator.
I'm thinking about trying to use a virtual delete, as sometimes I might have a child class that overloads delete, stored in a base class pointer. Technically, I don't really ever see this case coming to too much fruition, unless I have a tree of different node types (potentially dangerous idea in the first place if you ask me).
I just want to know what would be the potential pros and cons of a virtual, or non virtual, delete operator override.
delete keyword in C++ Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. Delete can be used by either using Delete operator or Delete [ ] operator. New operator is used for dynamic memory allocation which puts variables on heap memory.
The answer is yes. Destructor for each object is called. On a related note, you should try to avoid using delete whenever possible.
So delete is for managing the dynamic memory, but the destructor is a method of the class itself, which is always called when the object is getting freed from the memory (stack or heap).
You can’t explicitly declare operator delete
as virtual
.
It is a static member function, even if you do not supply the keyword static
.
But operator delete
is already virtual in the sense that the one defined in the most derived class is used. You might choose to think of it as if it's called by the destructor. It might even be. ;-)
C++11 §12.4/12:
“At the point of definition of a virtual destructor (including an implicit definition (12.8)), the non-array deallocation function is looked up in the scope of the destructor’s class (10.2), and, if no declaration is found, the function is looked up in the global scope.”
C++11 §12.5/4:
“If a delete-expression begins with a unary::
operator, the deallocation function’s name is looked up in global scope. Otherwise, if the delete-expression is used to deallocate a class object whose static type has a virtual destructor, the deallocation function is the one selected at the point of definition of the dynamic type’s virtual destructor (12.4).117 Otherwise, if the delete-expression is used to deallocate an object of classT
or array thereof, the static and dynamic types of the object shall be identical and the deallocation function’s name is looked up in the scope ofT
. If this lookup fails to find the name, the name is looked up in the global scope. If the result of the lookup is ambiguous or inaccessible, or if the lookup selects a placement deallocation function, the program is ill-formed.”
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