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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That sort of interleaving is not legal since C++17. A leak can't happen that way on a conformant C++17 compiler (though I still find repeating the type name bad on itself).
@StoryTeller: I didn't check, but are there deduction guides in C++17 for unique_ptr?
There aren't, and even the compiler generated ones are disabled by design. Chiefly because the deduction guide can't tell apart if it should deduce T* or T[] based on the argument to the constructor alone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.