Menu

Why prefer std::make_unique over new in std::unique_ptr?
📰

Why prefer std::make_unique over new in std::unique_ptr?

DEV Community: cpp·llzzz·3 days ago
#wQ8jure3
#devtocpp#devto#dev#unique_ptr#make_unique
Reading 0:00
15s threshold

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 ...…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.