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?
unique_ptr
takes a second template parameter which you should somehow allow for - that's different fromshared_ptr
. – Pomandermake_unique()
simply wraps anew
statement, it's not likemake_shared()
which is actually not trivial to implement correctly (it allocates the space for the reference count and the object at the same time). But good question though. – Sarchetmake_unique
with a custom deleter, because obviously it allocates via plain oldnew
and hence must use plain olddelete
:) – Unripemake_unique
would be limited tonew
allocation... well, it's fine if you want to write it, but I can see why something like that isn't part of the standard. – Pomandermake_unique
template since the constructor ofstd::unique_ptr
is explicit, and thus it is verbose to returnunique_ptr
from a function. Also, I'd rather useauto p = make_unique<foo>(bar, baz)
thanstd::unique_ptr<foo> p(new foo(bar, baz))
. – Chayachayotemake_unique
is coming inC++14
, see isocpp.org/blog/2013/04/trip-report-iso-c-spring-2013-meeting – Antagonistic