std::make_unique

From cppreference.com
< cpp‎ | memory‎ | unique ptr
 
 
 
Dynamic memory management
Uninitialized storage
(C++17)
(deprecated since c++17)
(deprecated since c++17)
(deprecated since c++17)
Garbage collection support
Miscellaneous
(C++11)
(C++11)
C Library
Low level memory management
 
 
Defined in header <memory>
template< class T, class... Args >
unique_ptr<T> make_unique( Args&&... args );
(1) (since C++14)
(only for non-array types)
template< class T >
unique_ptr<T> make_unique( std::size_t size );
(2) (since C++14)
(only for array types with unknown bound)
template< class T, class... Args >
/* unspecified */ make_unique( Args&&... args ) = delete;
(3) (since C++14)
(only for array types with known bound)

Constructs an object of type T and wraps it in a std::unique_ptr.

1) Constructs a non-array type T. The arguments args are passed to the constructor of T. This overload only participates in overload resolution if T is not an array type. The function is equivalent to:
unique_ptr<T>(new T(std::forward<Args>(args)...))
2) Constructs an array of unknown bound T. This overload only participates in overload resolution if T is an array of unknown bound. The function is equivalent to:
unique_ptr<T>(new typename std::remove_extent<T>::type[size]())
3) Construction of arrays of known bound is disallowed.

Parameters

args - list of arguments with which an instance of T will be constructed.
size - the size of the array to construct

Return value

std::unique_ptr of an instance of type T.

Exceptions

May throw std::bad_alloc or any exception thrown by the constructor of T. If an exception is thrown, this function has no effect.

Possible Implementation

// note: this implementation does not disable this overload for array types
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

Notes

Unlike std::make_shared (which has std::allocate_shared), std::make_unique does not have an allocator-aware counterpart. A hypothetical allocate_unique would be required to invent the deleter type D for the unique_ptr<T,D> it returns which would contain an allocator object and invoke both destroy and deallocate in its operator().