Advantages of using std::make_unique over new operator

niting picture niting · May 29, 2016 · Viewed 87.8k times · Source

What are the advantages of using std::make_unique over the new operator for initializing a std::unique_ptr?

In other words, why is

std::unique_ptr<SomeObject> a = std::make_unique(SomeObject(...))

better than doing

std::unique_ptr<SomeObject> a = new SomeObject(...)

I tried looking up a lot online and I do know that it is a good rule of thumb to avoid the operator new in modern C++, but I am not sure what the advantages are in this exact scenario. Does it prevent any kind of memory leaks that might happen? Is it faster to do a std::make_unique than to use new?

Answer

101010 picture 101010 · May 29, 2016

Advantages

  • make_unique teaches users "never say new/delete and new[]/delete[]" without disclaimers.

  • make_unique shares two advantages with make_shared (excluding the third advantage, increased efficiency). First, unique_ptr<LongTypeName> up(new LongTypeName(args)) must mention LongTypeName twice, while auto up = make_unique<LongTypeName>(args) mentions it once.

  • make_unique prevents the unspecified-evaluation-order leak triggered by expressions like foo(unique_ptr<X>(new X), unique_ptr<Y>(new Y)). (Following the advice "never say new" is simpler than "never say new, unless you immediately give it to a named unique_ptr".)

  • make_unique is carefully implemented for exception safety and is recommended over directly calling unique_ptr constructors.

When not to use make_unique

  • Don't use make_unique if you need a custom deleter or are adopting a raw pointer from elsewhere.

Sources

  1. Proposal of std::make_unique.
  2. Herb Sutter's GotW #89 Solution: Smart Pointers