Quick Q: Differences between std::make_unique and std::unique_ptr with new

Save to:
Instapaper Pocket Readability

Quick A: mostly for exception safety.

Recently on SO:

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 of new 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' use new rather than the previous rule to "'never' use new except when you make a unique_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).

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.