In the written question, the issue of "memory leaks" is frequently reviewed, one of which is:
A memory leak occurs when a pointer to a base class is pointed to a derived class object that is new, and then the delete pointer is changed.
The reason for this is that the pointer to the base class is pointing to the object of the derived class, the structure of the derived class object has not changed, and when we delete the base class pointer, only the memory of the data member that points to the base class is freed, and the memory that is used by the new member of the derived class still exists, which creates a memory leak
WORKAROUND: Declare the destructor of the base class as a virtual function, which is virtual destructor (virtual).
"Program Instance 1"
1#include <iostream>2 using namespacestd;3 4 classbase{5 Public:6~Base () {7cout<<"Base Deconstructor"<<Endl;8 }9 };Ten One classDerived: Publicbase{ A Public: -~Derived () { -cout<<"Derived Desconstuctor"<<Endl; the } - }; - - intMain () + { -Base *p=NewDerived; + A Deletep; at -}
"Run Results"
=================================================================
However, when we use the pointer of a derived class to point to a derived class and then delete the pointer, is there a memory leak? (asked a few side of the small partners, the results of a few sure), so the program to speak:
#include <iostream>using namespacestd;classbase{ Public: ~Base () {cout<<"Base Deconstructor"<<Endl; }};classDerived: Publicbase{ Public: ~Derived () {cout<<"Derived Desconstuctor"<<Endl; }};intMain () {Derived*p=NewDerived; Deletep;}
"Run Results"
Visible, this is no problem, with the same type of pointer pointing to the same type of object, how can cause problems?
Memory leak issues During the inheritance of C + + classes