You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用父类类型指针时如何触发子类析构函数?

解决父类指针销毁子类对象时不触发子类析构的问题

问题核心在于父类的析构函数不是虚函数。C++中,当通过基类指针删除派生类对象时,只有基类的析构函数被声明为虚函数,才会触发动态绑定,调用对应子类的析构函数;否则编译器只会执行基类的析构函数,导致子类的资源无法正确释放。

修改方案

将父类的析构函数声明为虚函数即可:

#include <iostream>

class Parent {
  public:
    // 声明为虚析构函数
    virtual ~Parent() { std::cout << "Parent destructor" << std::endl; }
};

class ChildA: public Parent {
  public:
    ~ChildA() { std::cout << "ChildA destructor" << std::endl; }
};

class ChildB: public Parent {
  public:
    ~ChildB() { std::cout << "ChildB destructor" << std::endl; }
};

int main() {
  Parent* myObj;
  myObj = new ChildA();
  delete myObj;
  myObj = new ChildB();
  delete myObj;

  return 0;
}

运行结果

修改后执行代码,会先调用子类的析构函数,派生类析构执行完毕后会自动调用基类析构,输出如下:

ChildA destructor
Parent destructor
ChildB destructor
Parent destructor

额外说明

只要一个类被用作基类,且存在通过基类指针销毁派生类对象的场景,就应该将基类的析构函数声明为虚函数。如果子类中有动态分配的内存或其他需要手动释放的资源,不这么做会导致内存泄漏或资源泄漏。

内容的提问来源于stack exchange,提问作者Sebastian Dine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 18:12:38