std::unique_ptr::reset and constructor exceptions

拥有回忆 提交于 2019-12-23 07:48:45

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/14269219/stdunique-ptrreset-and-constructor-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!