如果在构造函数中抛出异常,为对象自动删除的内存是否已分配? [英] Is memory allocated for an object automatically deleted if an exception is thrown in a constructor?

查看:119
本文介绍了如果在构造函数中抛出异常,为对象自动删除的内存是否已分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有以下代码:

class CFoo
{
public:
    CFoo()
    {
        iBar = new CBar();
    }
private:
    CBar* iBar;
};

....
CFoo* foo = new CFoo();

执行上述行时,将分配第一个内存来保存CFoo对象。但是如果行CBar()抛出一个异常(由于缺乏内存),系统是否自动释放之前分配给CFoo对象的内存?
我认为它必须,但是找不到任何明确的引用说。

When the above line is executed, first memory will be allocated to hold the CFoo object. But then if the line new CBar() throws an exception (due to lack of memory) does the system automatically deallocate the memory that was previously allocated to the CFoo object? I presume it must, but cannot find any explicit reference saying so. If it doesn't how can the memory be deallocated by the coder as it will not have been assigned to foo?

推荐答案

是的,如果没有,那么内存是如何被代码释放的呢? ,在这种情况下,为 CFoo 对象分配的内存将被释放。

Yes, the memory allocated for the CFoo object will be freed in this case.

因为失败分配导致 CFoo 构造函数无法成功完成 new-expression 将保证释放分配给 CFoo

Because the exception due to the failed allocation causes the CFoo constructor to fail to complete successfully the new-expression is guaranteed to free the memory allocated for that CFoo object.

此保证在ISO / IEC 14882:2003的5.3.4 [expr.new] / 17中规定。

This guarantee is specified in 5.3.4 [expr.new] / 17 of ISO/IEC 14882:2003.

请注意,始终建议将动态分配的结果分配给智能指针,以确保正确清理。例如,如果 CFoo 构造函数中还有其他代码,并抛出一个异常,则 CBar 对象早已成功分配构造函数将被泄露。

Note, that it is always advisable to assign the result of a dynamic allocation to a smart pointer to ensure proper clean up. For example, if there was further code in CFoo constructor and that threw an exception the CBar object already successfully allocated earlier in the constructor would be leaked.

这篇关于如果在构造函数中抛出异常,为对象自动删除的内存是否已分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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