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.