0

I cannot find the answer to this simple question:

given a class that throws in its constructor:

class Foo { 
    Foo() { throw std::logic_error(); }
}

if I create a new object from this class using the new operator, then do I leak the created object?

new Foo(); // << does this leak the Foo?
gexicide
  • 38,535
  • 21
  • 92
  • 152

2 Answers2

1

No, you won't have a memory leak. However, its fair to say that throwing in the constructor is usually considered as a bad practice as you may end up in half-constructing an object (depending on your class) and then you should rely on users of your class to detect construction failure by testing flag variables of some sort.

ladaManiak
  • 104
  • 1
  • 1
  • 6
0

No, if Foo's constructor throws, that means a Foo object never existed. There's no leak there. If you have data members that have been initialized priori, those members' individual destructors will run as the exception leaves the Constructor's block-scope

WhiZTiM
  • 21,207
  • 4
  • 43
  • 68