简体   繁体   中英

Virtual destructor use cases

I' ve read some articles, and as they say, main virtual destructor use cases are:

  • derived classes may have dynamic data allocation from heap, ie "own" that data object. So, they need some deletion routine in destructor. Deletion through base class pointer requires virtual declaration of destructors in all derived class till those with dynamic data allocation ( base class also requires it)

  • this class has virtual methods. But this is unclear for me. Just calling virtual methods through base class pointer always results in the-most- derived -realization calls. They only exclusion for that rule is construction phase. Literaly, during it this object is not a derived type yet, even if later will be. Ok, what about destruction phase? As I understood, the rule is in the backward order. No matter, was destructor of some class in hierarchy declared as virtual , during each destructor this pointer is used as if of this class type, any derived were already been destroyed due to virtual dr, or not destroyed (and that hypothetically may be ok in some design). Maybe this is the case, why dr must be virtual? Vtable will have entries for derived class, and calling virtual methods in some base class from dr will result in UB? Ok, but this rule applies only to case when this class calls some virtual methods in dr, and they do have realization in derived classes.

My opinion, that there is also may be a case with no dynamic data allocation, no virtual methods in all hierarchy, but still derived destructors may do some critical tasks upon deletion (syncs, unlocks and so on). And we need virtual dr in base class. May be such cases are results of bad design.

But anyway, developer of some public class cannot 100% know, if derived class will or not use some virtual methods in dr, or allocate dynamic data. So, am I correct to say, that any public class, not declared as final , has to declare dr as virtual? Only final keyword guarantees that any pointer to this class will always be of this type, and so, could be safely deleted non-virtually.

If a derived object is deleted through a pointer to the base class, then (and only then) the base class destructor must be virtual. Otherwise it is undefined behaviour . There are no other relevant rules.

If the class had a virtual function anyway, then no overhead is introduced. If the class did not have any other virtual functions, then the base class designer has to consider the trade between adding the runtime penalty of a virtual destructor, vs. the risk that a user of the class might try to delete a derived object through the base class pointer.

Here is a link to a similar discussion, with Standard quotes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM