9

If initialise a unique_ptr like this:

std::unique_ptr<Foo> i;
i.reset( new Foo() ); 

but an exception is thrown from Foo::Foo(), the question is: what happens with the memory allocated? how does unique_ptr avoid it being leaked? is this something handled inside new operator?

The destructor will certainly be called when the scope exits. Since the reset call is not invoked until new Foo() returns, it seems that this must be handled by new, by freeing the allocated memory when the exception leaves the constructor.

Is that what happens?

David G
  • 94,763
  • 41
  • 167
  • 253
lurscher
  • 25,930
  • 29
  • 122
  • 185
  • See http://stackoverflow.com/questions/4094996/what-happens-to-the-memory-allocated-by-new-if-the-constructor-throws – Jon Jan 10 '13 at 23:38

1 Answers1

13

If an exception is thrown in the constructor of Foo, then the reset function of the unique pointer never gets executed in the first place. Thus the unique pointer retains its original value.

A new expression doesn't leak memory if the object construction throws an exception.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084