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"));
Community
  • 1
  • 1
Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151
  • 1
    Probably because `unique` needs to construct an object and they thought it's better done explicit – Bartek Banachewicz Sep 25 '12 at 09:51
  • 3
    It's not the code that's inconsistent, it's the library. – Mark Garcia Sep 25 '12 at 09: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 '14 at 19:43

1 Answers1

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.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 2
    @hyde thanks. I updated it, but the new version does not have the sample implementation included in this answer (it can be found in the comments). – juanchopanza Jun 01 '13 at 21:54
  • 8
    and `make_unique` will also be available in C++14 in the same `memory` header http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique – user2485710 Dec 30 '13 at 11:29
  • 1
    N3656, adopted into C++14, has a standalone implementation: http://isocpp.org/files/papers/N3656.txt – Arto Bendiken Mar 22 '15 at 22:09