2

This question is a follow up to this question.

The accepted answer states:

make_unique is safe for creating temporaries whereas with explicit use of new you have to remember the rule about not using unnamed temporaries

I get the rough idea what is meant by this and I understand the example given, but how exactly does this work internally? What do these functions do exactly and where is the difference?

Jerome Reinländer
  • 1,227
  • 1
  • 10
  • 26

1 Answers1

7

What do these functions do exactly and where is the difference?

Nothing magical actually. They just transform user code from this:

f( std::unique_ptr<T1>{ new T1 }, std::unique_ptr<T2>{ new T2 } );

Into this:

f( make_unique<T1>(), make_unique<T2>() );

Just to avoid the scenario where the compiler orders the actions like the following, because it may do so until C++14 (included):

  • new T1
  • new T2
  • build first unique_ptr
  • build second unique_ptr

If the second step (new T2) throws an exception, the first allocated object has not yet been secured into a unique_ptr and leaks.

The make_unique function is actually simple to write, and has been overlooked for C++11. It has been easily introduced in C++14. Inbetween, everybody would write their own make_unique template, or google the one written by Stephen T. Lavavej.

As StoryTeller commented, since C++17, this interleaving is no more allowed.

Laurent LA RIZZA
  • 2,905
  • 1
  • 23
  • 41