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.
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
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.
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
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. Usestd::move(a), which leavesaempty (null). Containers ofunique_ptrwork (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 barenew, and keeps temporary objects exception safe: inf(std::unique_ptr<A>(new A), g())(pre-C++17) a throw fromg()could leak. Aunique_ptrconstructed directly fromnewis still fine in a single statement.make_uniquecannot take a custom deleter; construct theunique_ptryourself for that. - How to pass them. Pass
std::unique_ptr<T>by value to transfer ownership (a sink). PassT&orT*to merely use the object. Passstd::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 tounique_ptr<Base>; makeBase's destructor virtual. Aunique_ptrcan be converted into astd::shared_ptrby 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[]>callsdelete[];std::vectoris 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 incompleteImplonly if the destructor of the owning class is defined whereImplis complete. - Not for cycles or sharing. If several owners are needed, use
shared_ptr(withweak_ptrfor 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_ptris C++11 (replacing the removedstd::auto_ptr);make_uniqueC++14;constexprsupport in C++23.