构造函数抛出异常时释放内存 [英] Free memory when constructor throw exeception

查看:211
本文介绍了构造函数抛出异常时释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,



如果构造函数在堆上分配一些内存(使用new)之后抛出任何execpetion那么我们如何释放分配的内存。



我尝试了什么:



如果构造函数在分配了一些内存后抛出任何execpetion (在堆上使用new)然后我们如何释放分配的内存。

Hello,

If constructor is throwing any execpetion after allocating some memory (using new) on heap then how can we free that allocated memory.

What I have tried:

If constructor is throwing any execpetion after allocating some memory (using new) on heap then how can we free that allocated memory.

推荐答案

只需处理catch all块内的异常并重新抛出异常:

Just handle the exceptions inside a catch all block and rethrow the exception:
MyClass::MyClass() :
    member1(NULL)
    ,member2(NULL)
{
    // Initialise all pointers to memory to be allocated with NULL here or
    // as shown above.
    // Then delete can be safely called for them.
    //member1 = NULL;
    //member2 = NULL;
    try
    {
        // Memory allocation
        member1 = new Member1Type;
        member2 = new Member2Type;
    }
    catch (...)
    {
        // Cleanup here deleting all allocated memory
        delete member2;
        delete member1;

        // Re-throw the exception so that it can be handled again
        throw();
    }
}



因为释放内存通常也是在析构函数中完成的,所以编写一个可以从中调用的清理函数是很常见的。析构函数和上面的 catch 块。


另请参见:如果我的构造函数可能抛出异常,我应该如何处理资源? [ ^ ]


这篇关于构造函数抛出异常时释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆