unique_ptr没有在try / catch中调用析构函数

时间:2014-11-07 20:00:41

标签: c++

我有一个班级:

class Foo
{
public:
   Foo()
   {
       something_ = new int;
       throw std::exception("Bad");
   }
   ~Foo()
   {
       delete something_;
   } 
}

然后我有这个示例代码:

// Destructor is called
{
    std::unique_ptr<Foo> foo;
    foo.reset(new Foo());
}

// Destructor is NOT called
try
{
    std::unique_ptr<Foo> foo;
    foo.reset(new Foo());
}
catch(std::exception e)
{
}

我不清楚为什么在try / catch中没有调用析构函数。 unique_ptr范围是否因调用dtor而失效?

感谢您提供任何信息。

1 个答案:

答案 0 :(得分:2)

首先,从Foo的构造函数抛出异常,即在创建对象并将其分配给unique_ptr之前。

其次,如果构造函数没有成功,则无论如何都不会调用对象的析构函数。