One day a colleague was debugging a memory leak problem through vld. After a long time, he found me. I glanced at his code and found that the problem was exactly the same as what I encountered:
Class Base {
Public:
~ Base ();
};
Class Derived: public Base {
Privated:
Std: vector <int> m_data;
};
Base * obj = new Derived ();
Delete obj;
Of course, the actual code is much more complicated than this (this is also the reason that it takes a lot of time to discover the problem ). When vld reports a memory leak, the location of the error is new. This colleague checked the entire lifecycle of the object and confirmed that he correctly released the object.
The key to the problem is that the destructor of the Base class is not virtual. Because it is not virtual, When deleting a Base-type pointer, it will not call the Derived destructor of the Derived class. The destructor in the derived class is used to analyze the internal sub-objects, that is, m_data. In this way, memory leakage occurs.
This is actually a very low-level mistake. But it is not polite to say that C ++ has many examples where such a keyword or code location is incorrect may lead to another result. As a matter of fact, many books have come up with some guidelines for these tragedies to make them easy to follow. For example, I remember a book saying that if you think your class will be inherited, you 'd better add virtual to the destructor.