当我抛出异常时,内存会被释放吗? [英] Does the memory get released when I throw an exception?

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

问题描述

我正在与一些同事讨论在动态分配的类中引发异常时会发生什么.我知道先调用malloc,然后调用该类的构造函数.构造函数永远不会返回,那么malloc会发生什么?

I was debating with some colleagues about what happens when you throw an exception in a dynamically allocated class. I know that malloc gets called, and then the constructor of the class. The constructor never returns, so what happens to the malloc?

请考虑以下示例:

class B
{
public:
    B()
    {
        cout << "B::B()" << endl;
        throw "B::exception";
    }

    ~B()
    {
        cout << "B::~B()" << endl;          
    }
};

void main()
{
    B *o = 0;
    try
    {
        o = new B;
    }
    catch(const char *)
    {
        cout << "ouch!" << endl;
    }
}

已分配的内存o会发生什么,是否泄漏? CRT是否捕获构造函数的异常并释放内存?

What happens to the malloced memory o, does it leak? Does the CRT catch the exception of the constructor and deallocate the memory?

干杯!
丰富

推荐答案

new B();

解决两件事:

  • 使用运算符new()(全局变量或特定于类的变量,可能是语法为new (xxx) B()的位置变量)进行分配
  • 调用构造函数.
  • allocating with an operator new() (either the global one or a class specific one, potentially a placement one with the syntax new (xxx) B())
  • calling the constructor.

如果构造函数抛出异常,则调用相应的运算符delete.相应的删除是放置位置1的情况是唯一不使用:: operator delete()语法调用放置位置删除操作符的情况. delete x;delete[] x;不会调用展示位置删除操作符,也没有类似于new展示位置的语法来调用它们.

If the constructor throw, the corresponding operator delete is called. The case where the corresponding delete is a placement one is the only case where a placement delete operator is called without the syntax ::operator delete(). delete x; or delete[] x; don't call the placement delete operators and there is no similar syntax to placement new to call them.

请注意,虽然将调用B的析构函数,但在调用操作符delete之前,将销毁已构造的子对象(B的成员或B和B的基类).未被调用的构造函数是B的构造函数.

Note that while the destructor of B will not be called, already constructed subobjects (members or B and base classes of B) will be destructed before the call to operator delete. The constructor which isn't called is the one for B.

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

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