Differences between std::make_unique and std::unique_ptr with new
The motivation behind make_unique
is primarily two-fold:
make_unique
is safe for creating temporaries, whereas with explicit use ofnew
you have to remember the rule about not using unnamed temporaries.foo(make_unique<T>(), make_unique<U>()); // exception safe foo(unique_ptr<T>(new T()), unique_ptr<U>(new U())); // unsafe*
The addition of
make_unique
finally means we can tell people to 'never' usenew
rather than the previous rule to "'never' usenew
except when you make aunique_ptr
".
There's also a third reason:
make_unique
does not require redundant type usage.unique_ptr<T>(new T())
->make_unique<T>()
None of the reasons involve improving runtime efficiency the way using make_shared
does (due to avoiding a second allocation, at the cost of potentially higher peak memory usage).
* It is expected that C++17 will include a rule change that means that this is no longer unsafe. See C++ committee papers P0400R0 and P0145R3.
std::make_unique
and std::make_shared
are there for two reasons:
- So that you don't have to explicitly list the template type arguments.
- Additional exception safety over using
std::unique_ptr
orstd::shared_ptr
constructors. (See the Notes section here.)
It's not really about runtime efficiency. There is the bit about the control block and the T
being allocated all at once, but I think that's more a bonus and less a motivation for these functions to exist.
A reason why you would have to use std::unique_ptr(new A())
or std::shared_ptr(new A())
directly instead of std::make_*()
is being unable to access the constructor of class A
outside of current scope.