简体   繁体   English

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

[英]unique_ptr not calling destructor in try/catch

I have a class: 我有一堂课:

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

Then I have this sample code: 然后我有以下示例代码:

// 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)
{
}

I'm not quite clear on why the destructor isn't called in the try/catch. 我不清楚为什么在try / catch中没有调用析构函数。 Does the unique_ptr scope not expire for it to call the dtor? 唯一ID范围是否不会到期才能调用dtor?

Thanks for any information. 感谢您提供任何信息。

First, exception is thrown from the constructor of Foo , ie before the object is created and assigned to unique_ptr . 首先,从Foo的构造函数抛出异常,即在创建对象并将其分配给unique_ptr

Second, a destructor for an object is not going to be called anyway if a constructor did not succeed. 其次,如果构造函数没有成功,则无论如何都不会调用对象的析构函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM