In C++, why is std::make_unique preferred over writing std::unique_ptr<T>(new T(...)) yourself?
answer
- type written once
- no naked new in the code
- function arguments before C++17
- array form value-initializes
- deleters need the constructor
basics
~20 sstd::make_unique (C++14) names the type once and keeps new out of the code, so no raw owning pointer exists even briefly. Before C++17 it also prevented a leak when another argument of the same call threw.
solid answer
~40 s`std::make_unique<T>(args...)` returns `unique_ptr<T>(new T(std::forward<Args>(args)...))`, so `auto n = std::make_unique<Node>("camera");` names the type once and leaves no `new` in the code, which lets a team flag every remaining naked `new` in review. It used to matter for exceptions too: in `f(std::unique_ptr<A>(new A), g())` a pre-C++17 compiler could evaluate `new A`, then `g()`, and leak `A` if `g()` threw before the `unique_ptr` took it. C++17 made each parameter's initialization indeterminately sequenced, so that interleaving is gone, but the other reasons remain. The array form `std::make_unique<T[]>(n)` value-initializes the elements; C++20 added `std::make_unique_for_overwrite` to skip that. You still write `new` yourself for a custom deleter, a private constructor or a pointer that legacy code already allocated.
code
cpp · 18 lines#include <cstdio>
#include <memory>
#include <string>
struct Transform { float x, y, scale; }; // an aggregate: no constructor
struct Node {
std::string name;
explicit Node(std::string n) : name(std::move(n)) {}
};
int main() {
auto node = std::make_unique<Node>("camera"); // type written once, no new
auto xf = std::make_unique<Transform>(1.0f, 2.0f, 0.5f); // C++20: parenthesized aggregate init
auto ids = std::make_unique<int[]>(3); // new int[3](): all zero
auto scratch = std::make_unique_for_overwrite<char[]>(64);// C++20: left uninitialized
scratch[0] = '\0';
std::printf("%s %.1f %d%d%d\n", node->name.c_str(), xf->scale, ids[0], ids[1], ids[2]);
}go deeper
Recall that make_unique creates the object and its owner in one call, and that code should not need a naked new.
Explain the pre-C++17 argument-evaluation leak, why C++17 closed it, and how the array form and make_unique_for_overwrite differ in initialization.
Know the cases where make_unique cannot be used - custom deleters, private constructors, adopted pointers - and keep each new inside the statement that creates its owner.
A ban on naked new is cheap to enforce and pays back in reviews; decide where the few exceptions live and make them easy to audit.
## What std::make_unique is `std::make_unique` is a function template in `<memory>`, added in **C++14** (feature-test macro `__cpp_lib_make_unique`). The standard specifies it by its result: for a non-array `T`, `make_unique<T>(args...)` returns `unique_ptr<T>(new T(std::forward<Args>(args)...))`. It does nothing that you could not write by hand; its value is in what it removes from the call site. ## The reasons to prefer it - **The type appears once.** `auto node = std::make_unique<Node>("camera");` versus `std::unique_ptr<Node> node(new Node("camera"));`. Less repetition means fewer places for the two types to drift apart. - **No naked `new`.** If ownership is always created by `make_unique` (or `make_shared`), a code review or a static-analysis rule can treat any `new` outside a few low-level files as a defect. - **No window with a raw owning pointer.** The pointer goes straight from the allocation into the `unique_ptr` inside the library function. - **Historic exception safety.** Before C++17, the compiler could interleave the evaluation of different function arguments. In `f(std::unique_ptr<A>(new A), g())` it was allowed to run `new A`, then `g()`, and only then the `unique_ptr` constructor; if `g()` threw, the `A` leaked. C++17's rule that the initialization of each parameter, with all its side effects, is indeterminately sequenced with respect to that of any other parameter removed that interleaving, so this argument is now history — but it is still the reason most style guides adopted `make_unique` in the first place, and interviewers still ask about it. ## Arrays: std::unique_ptr<T[]> `std::unique_ptr<T[]>` is a partial specialization for arrays allocated with `new[]`. Its default deleter calls `delete[]`, and its interface changes accordingly: it provides `operator[]` and drops `operator*` and `operator->`. | expression | creates | elements | |---|---|---| | `std::make_unique<int[]>(3)` | `new int[3]()` | value-initialized (zero) | | `std::make_unique_for_overwrite<int[]>(3)` (C++20) | `new int[3]` | default-initialized (indeterminate for `int`) | | `std::make_unique<int[3]>()` | — | deleted: arrays of known bound are rejected | Holding `new Vertex[4]` in a plain `std::unique_ptr<Vertex>` compiles but deletes with `delete` instead of `delete[]`, which is undefined behaviour; AddressSanitizer reports it as `alloc-dealloc-mismatch` where that check is enabled. In most code `std::vector` is still the better owner of an array, because it knows its size. ## Reading the call site `make_unique` forwards its arguments to a constructor using **parentheses**, which has two visible consequences: - `std::make_unique<std::vector<int>>(3, 1)` builds a vector of three ones, not the two elements `{3, 1}`; to reach the `std::initializer_list` constructor you pass an explicit `std::initializer_list<int>{3, 1}`. - The result converts to a pointer to a base class, so `std::unique_ptr<Shape> s = std::make_unique<Circle>();` is the normal way to create a polymorphic object; the `Shape` needs a virtual destructor so that `delete` through the base pointer is defined. Neither form needs `new`, and both keep the allocation and the owner in a single expression. ## What changed in C++20 1. `std::make_unique_for_overwrite` creates the object with **default** initialization, for buffers that are written before they are read. 2. Parenthesized aggregate initialization lets `make_unique` build an aggregate: `std::make_unique<Transform>(1.0f, 2.0f, 0.5f)` compiles under C++20 and fails under C++17, because `make_unique` always uses parentheses, never braces. ## When you still write new - **A custom deleter.** `make_unique` always produces `std::default_delete<T>`; the deleter must be passed to the `unique_ptr` constructor. - **A private constructor.** `make_unique` is the function that calls `new`, so it cannot reach a constructor that only the class's own static factory may use; that factory writes `std::unique_ptr<Node>(new Node(...))` itself. - **Adopting a pointer** that a legacy API has already allocated. In each case, construct the `unique_ptr` in the same statement as the allocation so that no owning raw pointer survives a full expression. ## Common mistakes - Confusing it with `std::make_shared`: `make_unique` makes exactly the one allocation that `new` would, with no control block, so there is no allocation to save. - Reading `std::make_unique<int>(5)` as "five ints"; it is one `int` with the value 5, and only `make_unique<int[]>(5)` creates an array. - Assuming the array form leaves elements uninitialized; that is `make_unique_for_overwrite`. - Declaring `make_unique` obsolete because C++17 fixed argument evaluation; the leak was only one of its reasons. - Looking for a deleter argument; there is none, by design.
- What goes wrong with std::unique_ptr<Vertex> p(new Vertex[4]), and what should you write instead?It compiles, but `std::default_delete<Vertex>` calls `delete`, not `delete[]`, on memory from `new[]`: undefined behaviour. Use `std::unique_ptr<Vertex[]>`, ideally from `std::make_unique<Vertex[]>(4)`, which value-initializes the elements and offers `operator[]` instead of `*` and `->`. Usually `std::vector<Vertex>` is better still, since it also knows its size.
- Does C++17's evaluation-order change make std::make_unique unnecessary?No. C++17 removed the leak in `f(std::unique_ptr<A>(new A), g())` because one parameter is now fully initialized before another starts, but `make_unique` still writes the type once, keeps `new` out of reviewed code and leaves no raw owning pointer in any expression. Those remain the reasons to prefer it.
- make_unique puts the object and a control block in one allocation
- Since C++17 make_unique has no advantage over new
- make_unique<int>(5) creates an array of five ints
- make_unique accepts a custom deleter as an extra argument
- make_unique<T[]>(n) leaves the elements uninitialized
Assumes C++17 or later; C++20 added std::make_unique_for_overwrite and parenthesized aggregate initialization, which lets make_unique build aggregates.