Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Memory and Utilities

C++ std::unique_ptr class

Reference for std::unique_ptr: exclusive ownership, make_unique, move-only semantics, release, reset, get, custom deleters, arrays and factory functions.

std::unique_ptr<T> (header <memory>) is a smart pointer that owns a dynamically allocated object and destroys it automatically when the unique_ptr goes out of scope, is reset, or is assigned a new object. Exactly one unique_ptr owns a given object at any time, so ownership can be moved but never copied. It has the size of a raw pointer (with the default deleter) and no runtime overhead, which makes it the default choice for owning something on the heap.

Create one with std::make_unique<T>(args...), which allocates the object and wraps it in a single exception-safe step. Use it for polymorphic objects, for large objects, for objects whose lifetime is not tied to one scope, and for resources that are not memory at all (files, sockets) by supplying a custom deleter.

C++
auto p = std::make_unique<Widget>(42);   // owns a new Widget
p->run();                                // use like a pointer
auto q = std::move(p);                   // ownership moves; p is now empty
// q destroys the Widget at the end of its scope

Try it

C++ Ownership, move and the lifetime of the object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ release, get, arrays, custom deleters and polymorphism

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
template<class T, class Deleter = std::default_delete<T>> class unique_ptr;       // single object
template<class T, class Deleter> class unique_ptr<T[], Deleter>;                   // array

// Creation (header <memory>)
std::make_unique<T>(args...)                  // C++14
std::make_unique<T[]>(n)                      // C++14, value-initialized elements
std::make_unique_for_overwrite<T>()           // C++20, default-initialized (uninitialized ints)

// Observers and modifiers
T*   get() const noexcept;
T&   operator*() const;      T* operator->() const noexcept;   // single object
T&   operator[](size_t i) const;                                // array form
explicit operator bool() const noexcept;
T*   release() noexcept;
void reset(T* p = nullptr) noexcept;
void swap(unique_ptr& other) noexcept;
Deleter& get_deleter() noexcept;
Name Description
args... Arguments forwarded to the constructor of T.
n Number of elements for the array form.
Deleter A callable invoked with the raw pointer when the object must be destroyed. The default calls delete (or delete[] for arrays).
p A raw pointer that reset takes ownership of (it must be allocated in a way the deleter understands).

Returns: get() the stored pointer (may be null); release() the pointer and gives up ownership without deleting; operator bool is true if a pointer is stored; make_unique throws std::bad_alloc if allocation fails.

Errors / undefined behavior: dereferencing an empty unique_ptr is undefined behavior. Two unique_ptrs owning the same raw pointer (for example via reset(raw) or constructing from p.get()) cause a double delete. Calling delete on a pointer returned by get() is a double delete too. Deleting a derived object through a base pointer without a virtual destructor is undefined behavior.

Usage notes

  • Move-only. auto b = a; does not compile. Use std::move(a), which leaves a empty (null). Containers of unique_ptr work (vector<unique_ptr<T>>), but you must move the elements in and out, and copying the container is an error.
  • Prefer make_unique. std::make_unique<T>(...) avoids a bare new, and keeps temporary objects exception safe: in f(std::unique_ptr<A>(new A), g()) (pre-C++17) a throw from g() could leak. A unique_ptr constructed directly from new is still fine in a single statement. make_unique cannot take a custom deleter; construct the unique_ptr yourself for that.
  • How to pass them. Pass std::unique_ptr<T> by value to transfer ownership (a sink). Pass T& or T* to merely use the object. Pass std::unique_ptr<T>& only when the function may replace the object. Return by value to hand ownership to the caller, which is the recommended factory pattern.
  • Conversions. unique_ptr<Derived> converts implicitly to unique_ptr<Base>; make Base's destructor virtual. A unique_ptr can be converted into a std::shared_ptr by moving it, but not the other way.
  • Deleter and size. With a stateless deleter (default, empty class) the object is one pointer wide. A function-pointer or capturing-lambda deleter adds its size. The deleter is part of the type, which affects the type of containers.
  • Arrays. unique_ptr<T[]> calls delete[]; std::vector is usually a better choice because it knows its size. make_unique<int[]>(n) zero-initializes, make_unique_for_overwrite<int[]>(n) does not.
  • Incomplete types and Pimpl. unique_ptr<Impl> as a member works with an incomplete Impl only if the destructor of the owning class is defined where Impl is complete.
  • Not for cycles or sharing. If several owners are needed, use shared_ptr (with weak_ptr for back references). For non-owning access, a raw pointer or reference is the right tool.
  • Comparisons and hashing. unique_ptrs compare by stored pointer value; std::hash<std::unique_ptr<T>> exists. Sorting them orders by address, which is rarely meaningful.
  • Standard version. unique_ptr is C++11 (replacing the removed std::auto_ptr); make_unique C++14; constexpr support in C++23.