在C++的基类中,析构函数为什么声明为虚函数?

本文通过示例代码解释了C++中基类的析构函数为何通常声明为虚函数。若非虚函数,则通过基类指针删除派生类对象时只会调用基类析构函数,可能导致派生类资源泄露。虚析构函数确保正确调用派生类析构函数,避免资源问题。

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

在C++的基类中,析构函数为什么声明为虚函数,如果不声明为虚函数时,会发生什么?代码奉上:

#include <iostream>

class Base
{
public:
    Base() {
        std::cout << "Base::Create" << std::endl;
    }
    ~Base() {
        std::cout << "Base::Destory" << std::endl;
    }
};

class Derive :public Base
{
public:
    Derive() {
        std::cout << "Derive::Create" << std::endl;
        std::cout << "Derive::malloc memory" << std::endl;
    }
    ~Derive() {
        // 通常在析构函数中进行资源的释放工作
        std::cout << "Derive::free memory" << std::endl;
        std::cout << "Derive::Destory" << std::endl;
    }
};

int main(int argc, _TCHAR* argv[])
{
    Base* p = new Derive();
    // do something 
    delete p;
    return 0;
}

执行结果:

Base::Create
Derive::Create
Derive::malloc memory
Base::Destory
请按任意键继续. . .

       从上面的输出结果中看出,派生类中的析构函数没有进行调用。如果在派生类中申请了资源,在释放的时候(假设派生类的资源在析构函数中回收),可能会造成内存和资源的泄漏。这就是在基类中为什么析构函数一般为虚函数的原因。具体原因,当删除基类指针指向的派生类时,如果基类的析构函数不为虚函数的时候,不会触发动态绑定,所以不会调用派生类的析构函数。

        如果将基类中的析构函数声明为虚函数时:

class Base
{
public:
    Base() {
        std::cout << "Base::Create" << std::endl;
    }
    virtual ~Base() {
        std::cout << "Base::Destory" << std::endl;
    }
};
执行结果:
Base::Create
Derive::Create
Derive::malloc memory
Derive::free memory
Derive::Destory
Base::Destory
请按任意键继续. . .
OK

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值