虚析构

#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
posted @ 2022-07-11 14:59  thomas_blog  阅读(20)  评论(0编辑  收藏  举报