virtual析构函数的作用

本文通过实例详细解析了C++中虚析构函数的作用及其重要性,尤其是在避免内存泄漏方面。阐述了如何通过将析构函数声明为虚函数来确保正确清理派生类资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++ Primter中讲“在 C++ 中,基类必须指出希望派生类重写哪些函数,定义为 virtual 的函数是基类期待派生类重新定义的,基类希望派生类继承的函数不能定义为虚函数”。

 

析构函数是为了在对象不被使用之后释放它的资源,虚函数是为了实现多态。那么把析构函数声明为vitual有什么作用呢?,下面通过例子来说明一下vitual的用途。

using namespace std;

class Base
{
public:
  Base() {};     //Base的构造函数
  ~Base()        //Base的析构函数
  {
    cout << "the destructor of class Base!" << endl;
  };
  virtual void DoSomething() 
  {
    cout << "Do something in class Base!" << endl;
  };
};
    
class Derived : public Base
{
public:
  Derived() {};     //Derived的构造函数
  ~Derived()      //Derived的析构函数
  {
    cout << "the destructor of class Derived!" << endl;
  };
  void DoSomething()
  {
    cout << "Do something in class Derived!" << endl;
  };
};
    
int main()
{
  Derived *pTest1 = new Derived();   //Derived类的指针
  pTest1->DoSomething();
  delete pTest1;
    
  cout << endl;
    
  Base *pTest2 = new Derived();      //Base类的指针
  pTest2->DoSomething();
  delete pTest2;
    
  return 0;
}


先看程序输出结果:
1       Do something in class Derived!
2       the destructor of class Derived!
3       the destructor of class Base!
4      
5       Do something in class Derived!
6       the destructor of class Base!

从运行结果来看,pTest1运行比较正常,也好理解,pTest2运行了子类的Do something和父类的析构函数,并没有运行子类的析构函数,这样会造成内存泄漏。

pTest2运行了子类的Do something量因为父类的Do something加了virtual。

pTest2运行了父类的析构函数是因为父类的析构函数并没有加virtual,所以它并不会运行子类的析构函数。

如果Base的析构函数加上virtual,那么pTest1和pTest2运行过程一样。

总结:如果一个类有可能会被继承,那么它的析构函数最好加上virtual,不然出现内存泄漏问题找都找不到。

转载于:https://www.cnblogs.com/zhangnianyong/p/5588483.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值