代码如下:
#include <iostream>
using namespace std;class Base {public:Base() {cout << "Base" << endl;}~Base() {cout << "Base destructor" << endl;}
};class Derived : public Base {public:Derived() {cout << "Derived rush" << endl;p = new int(0);}~Derived() {cout << "Derived destructor" << endl;delete p;}private:int *p;
};void fun(Base *b) {delete b;
}int main() {Base *b = new Derived();fun(b);//输出:Base destructor
}
结果表明: 通过基类指针只能调用基类的析构函数, 这就造成派生类对象中动态分布的内存空间将不会得到释放, 从而造成“ 内存泄漏”。
代码如下:
#include <iostream>
using namespace std;class Base {public:virtual ~Base( ) {cout << "Base destructor" << endl;}
};class Derived: public Base {public:Derived( ) {p = new int(0) ;}~Derived( ) {cout << "Derived destructor" << endl;delete p;}private:int *p;
};void fun(Base *b) {delete b;
}int main( ) {Base *b = new Derived( );fun(b);return 0;
}