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_ptrtakes a second template parameter which you should somehow allow for - that's different fromshared_ptr. - Kerrek SBmake_uniquewith a custom deleter, because obviously it allocates via plain oldnewand hence must use plain olddelete:) - fredoverflowmake_uniquewould be limited tonewallocation... well, it's fine if you want to write it, but I can see why something like that isn't part of the standard. - Kerrek SBmake_uniquetemplate since the constructor ofstd::unique_ptris explicit, and thus it is verbose to returnunique_ptrfrom a function. Also, I'd rather useauto p = make_unique<foo>(bar, baz)thanstd::unique_ptr<foo> p(new foo(bar, baz)). - Alexandre C.make_uniqueis coming inC++14, see isocpp.org/blog/2013/04/trip-report-iso-c-spring-2013-meeting - stefan