简体   繁体   中英

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. Does the unique_ptr scope not expire for it to call the 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 .

Second, a destructor for an object is not going to be called anyway if a constructor did not succeed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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