This problem is occasionally encountered in practice, designing a timekeeper base class and some derived classes to record the time:
1 class TimeKeeper
2 {
3 public:
4 TimeKeeper ();
5 ~TimeKeeper();
6
7 };
8
9 class AtomicClock: public TimeKeeper {}; //原子钟
10 class WaterClock: public TimeKeeper {}; //水钟
When using, we may use the Factory factory method:
1 TimeKeeper* getTimeKeeper();//返回一个指针,指向一个派生类的动态分 配的对象
2
3 TimeKeeper* ptk = getTimeKeeper();//从继承体系中得到一 个动态分配对象
4
5 delete ptk;//负责的删除它
The problem occurs when you delete it, because PTK this pointer to the base class, the deleted instruction executes the base class Timekeeper destructor, which is not a virtual function.
In C + +, in this case its deletion behavior is not defined, the general will only delete the base class components, and the derived class elements are not deleted, which is the formation of resource leaks, corrupted data structures, the debugger waste a lot of time on the best way to Oh (quote the original translation).
The solution is to define a virtual destructor for a base class, so that the deletion behavior is implemented in the derived class, not just part of the deletion.
In general, a virtual destructor is defined as long as there is a virtual function in the class. However, if you do not have a virtual function in a class, you do not need and should not define a virtual destructor, which is not only useless, but also adds additional expense and creates a lot of compatibility problems because the virtual mechanism is unique to C + +.
In addition, many classes in C + + implementations are not virtual, such as: String,stl in the Vector,list, Set,trl::unordered_map, if you inherit them is likely to be the error, so the author reminded : Reject inheritance of standard containers or other classes that have only non-virtual destructors!