【问题标题】:Constructor Exception and Dynamic Allocation [duplicate]构造函数异常和动态分配
【发布时间】:2014-01-05 15:57:20
【问题描述】:

我想知道如果一个对象是动态分配的,构造函数抛出异常,这个对象还需要删除吗?

class Doom
{
public:

   Doom() { throw 0; }

private:

   int pad;

};

int main()
{
    try
    {
        // memory is allocated for Doom but construction fails
        // is the memory deallocated if construction fails here ?
        Doom* doom = new Doom(); 
    }
    catch(int ex)
    {
        // ...
    }
}

【问题讨论】:

  • 使用unique_ptr。永远不要考虑删除内存或再次泄漏。
  • @Dave: 使用 unique_ptr 是不够的 - foo(unique_ptr(new bar()), unique_ptr(new bar()));仍然可以泄漏。你需要make_unique/make_shared
  • @JoeGauterin:想详细说明这将如何泄漏?编辑:啊,我想我现在看到了,调用了 new bar(),然后在为另一个 bar 构造 unique_ptr 之前调用了另一个 new bar(),但是这个抛出异常,导致前一个泄露。
  • 这篇 Herb Sutter 文章深入讲解 - herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers

标签: c++


【解决方案1】:

没有。没有什么可删除的,因为该对象从未被构造。编译器将负责释放已分配的内存。

【讨论】:

    猜你喜欢
    • 2011-03-11
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 2011-06-11
    • 1970-01-01
    相关资源
    最近更新 更多