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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With