return new 内存泄漏

发布时间 2023-09-01 15:20:50作者: 夕西行

样例如下:

#include <iostream>

class B
{
public:
    int Fun()
    {
        return 100;
    }
}

class A
{
public:
    B* CreateB()                    //new了个B对象
    {
        return new B();
    }
}

int main()
{
    A *aa=new A();
    std::cout<<A->CreateB()->Fun(); //new的B对象没有被delete掉,内存泄漏

    delete aa;
    aa=nullptr;

    return 0;
}

解决方式:

1、方式一

智能指针【推荐此方式】

#include <memory>               //for unique_ptr

class A
{
public:
    std::unique_ptr<B> CreateB()                    //new了个B对象
    {
        std::unique_ptr<B> up_b(new B());           //使用智能指针,会自动释放资源
        return up_b;
    }
}

2、方式二

再写个删除函数

class A
{
public:
    B* CreateB()                    //new了个B对象
    {
        return new B();
    }
    void DeleteB(B** pObj)          //释放B对象
    {
        if(pObj!=nullptr && *pObj!=nullptr)
        {
            delete *pObj;
            *pObj=nullptr;
        }
    }
}

int main()
{
    A *aa=new A();
    B *bb=aa->CreateB();    //其中new了个B对象
    std::cout<<bb->Fun(); 

    aa->DeleteB(&bb);       //释放B对象

    delete aa;
    aa=nullptr;

    return 0;
}

3、方式三

int main()
{
    A *aa=new A();
    B *bb=aa->CreateB();    //其中new了个B对象
    std::cout<<bb->Fun(); 

    delete bb;              //释放B对象
    bb=nullptr;
    delete aa;
    aa=nullptr;

    return 0;
}