std::make_unique
std::make_unique<T>(args...) allocates a T with new and returns a std::unique_ptr<T> that owns it. It is the default way to create a unique pointer. make_unique<T[]>(n) creates an array.
Detailed Explanation
unique_ptr<T>(new T(args)) works and has a hole. In f(unique_ptr<T>(new T), unique_ptr<U>(new U)), the compiler may new T, new U, then construct the first unique_ptr. If new U throws, T leaks because no unique_ptr owns it yet. make_unique ties allocation and ownership in one function, so that interleaving cannot leak.
It is also shorter and it keeps new out of application code. Exception-safety and readability are the same recommendation.
C++14 added make_unique. C++20 added make_unique_for_overwrite which default-initialises (does not zero) trivially-constructible T or arrays — useful for a buffer you will fill immediately.
There is no make_unique with a custom deleter. You write unique_ptr<T, D>(new T, D{}) or wrap the factory. For FILE*, a small helper that fopens and returns unique_ptr<FILE, FileCloser> is the pattern.
make_shared is the sibling for shared_ptr and also fuses the control block. Do not use make_shared when you meant unique ownership; make_unique documents "one owner".
Arrays: auto p = std::make_unique<int[]>(n); value-initialises n ints (zeros). Prefer vector<int>(n) unless you need a pointer API.
make_unique cannot call a private constructor unless it is a friend. A class with a private constructor needs a static factory that can new internally, or a std::unique_ptr<T>(new T) inside a member.
Do not make_unique and then release() into a raw pointer "for a C API" without a plan to get ownership back. Prefer the C API that takes a deleter, or keep the unique_ptr alive for the duration of the call and pass get().
Code Examples
#include <iostream>
#include <memory>
#include <string>
struct User {
std::string name;
explicit User(std::string n) : name(std::move(n)) {}
};
int main() {
auto u = std::make_unique<User>("ada");
std::cout << u->name << '\n'; // prints: ada
}#include <memory>
void take(std::unique_ptr<int> a, std::unique_ptr<int> b);
int main() {
// Safe: each make_unique owns before the next allocation can throw.
take(std::make_unique<int>(1), std::make_unique<int>(2));
}
void take(std::unique_ptr<int>, std::unique_ptr<int>) {}Common Gotchas
`make_unique<T[]>(n)` value-initialises
a large `char` buffer is zeroed. Use `make_unique_for_overwrite` (C++20) or `vector` if you will overwrite immediately.
No custom deleter overload
write a factory that returns `unique_ptr<T, D>`.
Using `make_unique` on an abstract type
does not compile. `make_unique<Derived>()` and store in `unique_ptr<Base>`.
Private constructors
`make_unique` is not a friend by default. Add a factory function inside the class.