0

I was wondering if an object is dynamically allocated and the constructor throws an exception, does the object still need to be deleted ?

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)
    {
        // ...
    }
}
johndoe
  • 303
  • 2
  • 13
  • Use `unique_ptr`. Never think about deleting memory or having leaks again. – David Dec 17 '13 at 18:32
  • @Dave: Using `unique_ptr` isn't enough - `foo(unique_ptr(new bar()), unique_ptr(new bar()))`; can still leak. You need `make_unique`/`make_shared`. – JoeG Dec 17 '13 at 18:38
  • @JoeGauterin: Care to elaborate more about how that would leak ? Edit: ah i think i see it now, new bar() is called, then the other new bar() is called before the unique_ptr is constructed for the other bar but this one throws an exception leaving the previous one leaked. – johndoe Dec 17 '13 at 21:50
  • 1
    This Herb Sutter article explains in depth - http://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/ – JoeG Dec 18 '13 at 10:43

1 Answers1

4

No. There's nothing to delete, because the object never got constructed. The compiler will take care of freeing the memory that was allocated.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165