54

Possible Duplicate:
make_unique and perfect forwarding

Why does C++11 have a make_shared template, but not a make_unique template?

This makes code very inconsistent.

auto x = make_shared<string>("abc");
auto y = unique_ptr<string>(new string("abc"));
3
  • 1
    Probably because unique needs to construct an object and they thought it's better done explicit Sep 25, 2012 at 9:51
  • 3
    It's not the code that's inconsistent, it's the library. Sep 25, 2012 at 9:51
  • 1
    The copy constructor for unique_ptr is private. So make_unique doesn't work without "return value optimization". My guess is according to the language spec this optimization is not mandatory.
    – bop
    Nov 22, 2014 at 19:43

1 Answer 1

64

According to Herb Sutter in this article it was "partly an oversight". The article contains a nice implementation, and makes a strong case for using it:

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

Update: The original update has been updated and the emphasis has changed.

3

Not the answer you're looking for? Browse other questions tagged or ask your own question.