标签:
Without Virtual Destructor(虚析构函数)
class A{
public:
int a = 3;
A()
{
cout <<"A()..."<< endl;
}
~A()
{
cout << "~A()..." << endl;
}
};
class B : public A{
public:
int b;
B(){
cout << "B()..." << endl;
}
~B(){
cout << "~B()..." << endl;
}
};
void main()
{
A *a = new B;
delete a;
system("pause");
}
result:
A()...
B()...
~A()...
Press any key to continue . . .
没有~B(),内存泄漏!!
Virtual Destructor(虚析构函数)
class A{
public:
int a = 3;
A()
{
cout <<"A()..."<< endl;
}
virtual ~A()
{
cout << "~A()..." << endl;
}
};
class B : public A{
public:
int b;
B(){
cout << "B()..." << endl;
}
~B(){
cout << "~B()..." << endl;
}
};
void main()
{
A *a = new B;
delete a;
system("pause");
}
result:
A()...
B()...
~B()...
~A()...
Press any key to continue . . .
防止内存泄漏!!
[C++] Virtual Destructor(虚析构函数)
标签:
原文地址:http://www.cnblogs.com/tianhangzhang/p/4966672.html