0

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.

BigHands79
  • 229
  • 4
  • 18

1 Answers1

3

First, exception is thrown from the constructor of Foo, i.e. 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.

AlexD
  • 32,156
  • 3
  • 71
  • 65
  • So how come in the first example the destructor is being called? – BigHands79 Nov 10 '14 at 13:36
  • 1
    @BigHands79 It should not. Could it be that you see something like a debug window which offers you to ignore the unhandled exception? And if you do, perhaps execution continues right after `throw`, but the application state is messed up. – AlexD Nov 10 '14 at 14:04
  • I was running the code in Debug inside VS2012 and hitting "Continue" when the exception happened. The exception dialog that pops up is an unhandled exception message, so by pressing "Continue", VS2012 is probably interpreting "Continue" as "Ignore. This makes sense. Thanks for your help. – BigHands79 Nov 10 '14 at 14:35