Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::unique_ptr::reset and constructor exceptions

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?

like image 966
lurscher Avatar asked Jan 10 '13 23:01

lurscher


1 Answers

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.

like image 131
Kerrek SB Avatar answered Oct 01 '22 16:10

Kerrek SB