I have two classes, base_class and derived_class and the following code:
base_class *ptr = new derived_class;
delete ptr;
Will this code produce a memory leak? If so, how should I deal with it?
It won't leak the object you are deleting, its memory block will be freed.
If you have not declared the destructor in base_class
to be virtual then it will leak any dynamically allocated objects contained within derived_class
that rely on the destructor of derived_class
being called to free them. This is because if the destructor is not virtual, the derived_class
destructor is not called in this case. It also means that destructors of "embedded objects" within derived_class
will not automatically be called, a seperate but additional problem, which can lead to further leaks and the non-execution of vital cleanup code.
In short, declare the destructor in base_class
to be virtual and you can safely use the technique you have presented.
For a coded example, see:
In what kind of situation, c++ destructor will not be called?
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