Deleting a derived object via a pointer to its base class

前端 未结 1 411
日久生厌
日久生厌 2021-01-02 09:02

I have two classes, base_class and derived_class and the following code:

base_class *ptr = new derived_class;
delete ptr;

Will this code pr

相关标签:
1条回答
  • 2021-01-02 09:50

    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?

    0 讨论(0)
提交回复
热议问题