问题
I know you shouldn't call any virtual function in the ctor or dtor of the base class, but what about from that of the most derived class? Should be fine right? E.g.
class base {
...
virtual void free() = 0;
};
class child : public base {
...
free() {/* free memory */}
~child() {free();}
};
回答1:
Well, you can do it, but the dynamic type of *this
inside child::~child()
is child
, and not anything more derived. So when you have a further derived class class foo : child
which overrides free()
, then the overridden function will not be called.
回答2:
There's nothing wrong with calling a virtual function from a constructor or destructor, base class or otherwise. But you have to know what it does: the dynamic type is the class being constructed or destroyed, so it won't call an override in a class derived from the one that's being constructed or destroyed. In particular, if the function is pure virtual, you won't get an override, and the behavior is undefined. So a good rule is "don't call pure virtual functions from constructors or destructors. In your example, class::free
is not pure virtual, so there's no problem calling it.
来源:https://stackoverflow.com/questions/16530255/pure-virtual-call-in-destructor-of-most-derived-class