Search code examples
c++c++11unique-ptr

How to implement make_unique function in C++11?


My compiler doesn't support make_unique. How to write one?

template< class T, class... Args > unique_ptr<T> make_unique( Args&&... args );

Solution

  • Copied from make_unique and perfect forwarding (the same is given in Herb Sutter's blog)

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

    If you need it in VC2012, see Is there a way to write make_unique() in VS2012?


    Nevertheless, if the solution in sasha.sochka's answer compiles with your compiler, I would go with that one. That is more elaborate and works with arrays as well.