虚析构
#include <iostream>
class Person
{
public:
Person()
{
std::cout << "Person" << std::endl;
}
~Person()
{
std::cout << "~Person" << std::endl;
}
public:
};
class Student: public Person
{
public:
Student()
{
std::cout << "Student" << std::endl;
age = new(int);
}
~Student()
{
std::cout << "~Student" << std::endl;
delete age;
}
public:
int *age;
};
int main()
{
Person *p = new Student;
delete p;
return 0;
}
/* 父类指针在析构时,不会调用子类析构函数。导致子类堆区数据内存泄漏 */
$ ./a.out
Person
Student
~Person
修改虚析构
virtual ~Person()
{
std::cout << "~Person" << std::endl;
}
$ ./a.out
Person
Student
~Student
~Person