fredoverflow fredoverflow - 4 months ago 31
C++ Question

make_unique and perfect forwarding

Why is there no

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
nicely and only mentions the type once.

Anyway, here is my attempt at an implementation of

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
stuff to compile, but I'm not sure if it's correct. Is it? What exactly does
mean? What does the compiler make of that?


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.