1、当申请的动态内存指针是基类指针时,需考虑内存的泄漏情况如下代码:
#include <iostream>
using namespace std;class A
{
public:
A(){
cout << "constructor A" << endl;
}
~A()
{
cout << "destructor A" << endl;
}
};
class B:public A
{
public:
B(){
cout << "constructor B" << endl;
}
~B(){
cout << "destructor B" << endl;
}
};
int main(void)
{
A *p = new B;//基类指针时才会考虑到虚函数和虚析构函数
delete p;
}
输出:
constructor A
constructor B
destructor A
可知B类的析构函数没被调用,当B类中的成员变量有指针时,就会导致内存的泄漏。
#include <iostream>
using namespace std;class A
{
public:
A(){
cout << "constructor A" << endl;
}
virtual ~A()
{
cout << "destructor A" << endl;
}
};
class B:public A
{
public:
B(){
cout << "constructor B" << endl;
}
~B(){
cout << "destructor B" << endl;
}
};
int main(void)
{
A *p = new B;
delete p;
}
输出:
constructor A
constructor B
destructor B
destructor A
此时虚析构函数的的定义就会调用B类的析构函数。
2、当定义的是派生类指针就不会出现析构函数不被调用的情况
#include <iostream>
using namespace std;class A
{
public:
A(){
cout << "constructor A" << endl;
}
~A()
{
cout << "destructor A" << endl;
}
};
class B:public A
{
public:
B(){
cout << "constructor B" << endl;
}
~B(){
cout << "destructor B" << endl;
}
};
int main(void)
{
B *p = new B;
delete p;
}
输出:constructor A
constructor B
destructor B
destructor A
此时当B中的析构函数被调用