Let me quote part of the section in Professional C++ 5th. ed.(Page 237):
Before C++17, you had to use
make_unique()
... Consider the following call to a function called foo():
foo(unique_ptr<Simple> { new Simple{} }, unique_ptr<Bar> { new Bar { data() } });
If the constructor of
Simple
orBar
, or thedata()
function, throws an exception, depending on your compiler optimizations, it was possible that either aSimple
or aBar
object would be leaked. Withmake_unique()
, nothing would leak:
foo(make_unique<Simple>(), make_unique<Bar>(data()))
Since C++17, both calls to
foo()
are safe, but I still recommend usingmake_unique()
as it results in code that is easier to read.
I know why it's not safe before C++17 since new
may happen first and data()
may be called then before the new
'd result is passed to unique_ptr
, so when an exception throws, memory leaks happen. But why does it become safe since C++17?