fredoverflow fredoverflow - 3 months ago 16
C++ Question

make_unique and perfect forwarding

Why is there no

std::make_unique
function template in the standard C++11 library? I find

std::unique_ptr<SomeUserDefinedType> p(new SomeUserDefinedType(1, 2, 3));


a bit verbose. Wouldn't the following be much nicer?

auto p = std::make_unique<SomeUserDefinedType>(1, 2, 3);


This hides the
new
nicely and only mentions the type once.

Anyway, here is my attempt at an implementation of
make_unique
:

template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}


It took me quite a while to get the
std::forward
stuff to compile, but I'm not sure if it's correct. Is it? What exactly does
std::forward<Args>(args)...
mean? What does the compiler make of that?

Answer

Herb Sutter, chair of the C++ standardization committee, writes on his blog:

That C++11 doesn’t include make_unique is partly an oversight, and it will almost certainly be added in the future.

He also gives an implementation that is identical with the one given by the OP.

Edit: std::make_unique now is part of C++14.