In modern C++, when you need a std::unique_ptr , the idiomatic way to create it is:
auto ptr = std :: make_unique < MyClass > ();
Enter fullscreen mode
Exit fullscreen mode
rather than manually new -ing the object inside the unique_ptr constructor:
std :: unique_ptr < MyClass > ptr { new MyClass ()};
Enter fullscreen mode
Exit fullscreen mode
std::make_unique was introduced in C++14 to fill a gap that std::make_shared had already covered for shared ownership. It is a small function template, but it carries several important advantages. This article walks through every reason to prefer it, notes what changed in C++17 and C++20, and covers the cases where you still need the raw new form.
the implementation of std::make_unique is roughly the following:
namespace std { template < typename T , typename ... Args > std :: unique_ptr < T > make_unique ( Args ...…