关于C++虚析构函数的一点笔记

本文通过示例程序详细解析了C++中虚析构函数如何避免内存泄漏问题,尤其是在多态环境下,确保派生类析构函数正确调用,释放所有资源。

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

C++虚析构函数可以防止内存泄漏

示例程序

#include <iostream>
#include <string>

using namespace std;

class Base1
{
public:
    Base1()
    {
        cout << "Base1()" << endl;
    }
    ~Base1()
    {
        cout << "~Base1()" << endl;
    }
};

class Base2
{
public:
    Base2()
    {
        cout << "Base2()" << endl;
    }
    virtual ~Base2()
    {
        cout << "~Base2()" << endl;
    }
};

class Derived1:public Base1
{
public:
    Derived1()
    {
        name=new string("NULL");
        cout<<"Derived1()"<<endl;
    }
    Derived1(const string& n)
    {
        name=new string(n);
        cout<<"Derived1()"<<endl;
    }
    ~Derived1()
    {
        delete name;
        cout << "Derived1 has been deleted." << endl;
    }
private:
    string* name;
};

class Derived2:public Base2
{
public:
    Derived2()
    {
        name=new string("NULL");
        cout<<"Derived2()"<<endl;
    }
    Derived2(const string& n)
    {
        name=new string(n);
        cout<<"Derived2()"<<endl;
    }
    ~Derived2()
    {
        delete name;
        cout << "Derived2 has been deleted." << endl;
    }
private:
    string *name;
};

int main(void)
{
    Base1* b1=new Derived1();
    Base2* b2=new Derived2();
    delete b1;
    delete b2;
    return 0;
}

输出结果
Base1()
Derived1()
Base2()
Derived2()
~Base1()
Derived2 has been deleted.
~Base2()


可以看到输出结果中,只调用了Base1的析构函数,但没有调用Derived1的析构函数,此时Derived1的部分内存并没有被释放,因此造成内存泄露。
将基类的析构函数改为虚函数,再用基类指针指向派生类对象时可以调用派生类对象的析构函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值