Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 171 ยท Pointers, References and Memory

Smart Pointers: std::unique_ptr

Learn C++ std::unique_ptr - exclusive ownership, std::make_unique, moving ownership, passing to functions, custom deleters, arrays and polymorphic objects.

std::unique_ptr<T> is a pointer that owns the object it points to. When the unique_ptr is destroyed (at the end of a scope, when its containing object dies, or when an exception passes through), it deletes the object for you. There is no delete to forget, no double delete, and no leak on early return. And it costs nothing: a unique_ptr with the default deleter is the same size as a raw pointer and compiles to the same machine code.

The "unique" means exclusive ownership: at any moment exactly one unique_ptr owns a given object. You can't copy it (that would create two owners), but you can move it, which transfers ownership from one unique_ptr to another. That one rule makes ownership visible in your types: a function returning std::unique_ptr<Widget> says "you own this now", and a function taking one says "give it to me". This lesson covers creating, using and moving unique pointers, passing them to functions, custom deleters for non-memory resources, arrays, and the most important use of all: owning polymorphic objects. It builds on Dynamic Memory: new and delete.

Creating a unique_ptr with make_unique

Include <memory> and create the object with std::make_unique<T>(args...). It allocates a T, constructs it with the arguments and returns a std::unique_ptr<T> that owns it.

C++ make_unique and automatic cleanup

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.

You use a unique_ptr just like a raw pointer: *p gives the object, p->member reaches members, and it converts to bool in conditions (if (p) is true when it owns something). A default-constructed std::unique_ptr<T> is empty (null).

Why make_unique instead of std::unique_ptr<Sensor>(new Sensor{"thermo-1"})? Both work, but make_unique:

  • doesn't repeat the type name,
  • never shows a raw new in your code, so a search for new finds only code that needs review,
  • can't be misused by accidentally handing the same raw pointer to two unique_ptrs.

std::make_unique<T>() value-initializes (an int becomes 0). C++20's std::make_unique_for_overwrite<T>() skips that for buffers you're about to fill anyway.

Ownership moves, it doesn't copy

Copying a unique_ptr is a compile error: two owners would both try to delete the object. To hand ownership to someone else, move it with std::move. The source becomes empty (null), and the destination now owns the object.

C++ Moving ownership between unique_ptrs

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.

std::move doesn't move anything by itself; it just marks first as something that may be moved from, which selects the move constructor. Moves are explained fully in Move Semantics. After a move, a unique_ptr is guaranteed to be null. It's safe to test or reassign, but don't dereference it.

The member functions you'll use most:

Member What it does
get() returns the raw pointer without giving up ownership
reset(p) deletes the current object (if any) and takes ownership of p; reset() just empties
release() gives up ownership and returns the raw pointer; you must delete it now
swap(other) exchanges the owned objects
operator bool true if it owns an object

release() is the dangerous one: the object stops being managed. Use it only to hand ownership to an API that will free it (for example, a C library that takes ownership). Calling p.release(); and ignoring the result is a silent leak (GCC doesn't warn about it), so when you only want to delete the object and empty the pointer, call reset() instead.

Passing unique_ptrs to functions

How you pass a unique_ptr should say what the function does with ownership. These are the conventions used across the C++ world:

Parameter Meaning
T& or const T& "I just use the object." The function doesn't care how it's owned. Most functions should look like this.
T* "I use the object, and it might be null." Pass p.get().
std::unique_ptr<T> (by value) "Give me ownership." The caller must std::move it in.
std::unique_ptr<T>& "I might replace or reset your pointer." Rare.
returns std::unique_ptr<T> "Here's a new object; you own it now."
C++ Ownership in function signatures

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.

Notice three things. Returning a local unique_ptr from make_task needs no std::move: returned locals are moved automatically. Passing the result of a function call (make_task(...)) straight into push needs no std::move either, because it's a temporary. And std::vector<std::unique_ptr<Task>> works perfectly: the vector moves its elements when it grows, and clear() (or the vector's destructor) deletes every task.

A common mistake is writing void describe(const std::unique_ptr<Task>& task). It works, but it needlessly forces callers to own their object through a unique_ptr. Take const Task& (or const Task* if null is allowed) and let the caller write describe(*p). Functions that don't deal with ownership shouldn't mention smart pointers.

unique_ptr as a class member

A unique_ptr member gives a class exclusive ownership of a heap object with zero cleanup code. The compiler-generated destructor destroys the member, which deletes the object. The class automatically becomes move-only: it can be moved but not copied, which is usually exactly right for a class that owns a unique resource. (If you need copies, you write a copy constructor that clones the owned object; see Copy Constructors and Copy Assignment.)

C++
class Document {
public:
    explicit Document(std::string title)
        : title_{std::move(title)}, cache_{std::make_unique<RenderCache>()} {}
    // no destructor needed: cache_ cleans up after itself
private:
    std::string title_;
    std::unique_ptr<RenderCache> cache_;
};

This is the Rule of Zero in action: by letting members manage resources, you never write a destructor, copy constructor or assignment operator yourself.

Polymorphism: owning objects through a base pointer

The single most important use of unique_ptr is holding objects of different derived classes through a pointer to their base class. A std::vector<Shape> can't hold circles and squares (they'd be sliced to plain Shapes), but a std::vector<std::unique_ptr<Shape>> can.

C++ A vector of polymorphic shapes

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.

A std::unique_ptr<Circle> converts implicitly to a std::unique_ptr<Shape>, just as a Circle* converts to a Shape*. When the vector is destroyed at the end of main, each unique_ptr<Shape> deletes its object through a Shape*. That only calls the right destructor because Shape has a virtual destructor. Without it, deleting a Circle through a Shape* is undefined behavior. Virtual Functions and Polymorphism explains why in depth, and Abstract Classes and Interfaces builds on this factory pattern.

Custom deleters: managing any resource

By default a unique_ptr<T> calls delete. You can give it a different deleter, which makes it a general-purpose RAII wrapper for anything with an "acquire" and a "release" function: C FILE* handles, sockets, library handles, memory from malloc.

The deleter is part of the type: std::unique_ptr<T, Deleter>. A stateless deleter (a lambda with no captures, or a small struct) adds no size.

C++ unique_ptr closing a C FILE automatically

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.

The output shows the first file being closed at the end of its block, before the reading starts, and the second when main ends. A unique_ptr never calls its deleter on a null pointer, so a failed fopen is handled safely. (For real file work, C++ streams are already RAII types; see Reading and Writing Text Files. The pattern matters for C libraries that have no C++ wrapper.)

A lambda works too, but then you need its type: auto closer = [](std::FILE* f) { std::fclose(f); }; std::unique_ptr<std::FILE, decltype(closer)> p{std::fopen(...), closer};. In C++20 and later you can write decltype([](std::FILE* f) { std::fclose(f); }) directly in the type.

unique_ptr for arrays

std::unique_ptr<T[]> owns an array allocated with new[] and calls delete[]. It offers operator[] instead of * and ->, and std::make_unique<T[]>(n) creates the array value-initialized:

C++
auto buffer = std::make_unique<int[]>(5);   // five ints, all 0
buffer[2] = 42;
// buffer.size()  // doesn't exist: the size isn't stored

It's useful mainly for interfacing with C APIs or for a fixed buffer you never resize. In most code std::vector<T> is better: it knows its size, can grow, and has bounds-checked at().

Common mistakes

C++
// 1. Two owners of one raw pointer: double delete.
Widget* raw = new Widget;
std::unique_ptr<Widget> a{raw};
std::unique_ptr<Widget> b{raw};       // BUG: both will delete raw

// 2. Owning something that wasn't from new.
Widget local;
std::unique_ptr<Widget> c{&local};    // BUG: deletes a stack object

// 3. Keeping a raw pointer after giving ownership away.
auto owner = std::make_unique<Widget>();
Widget* peek = owner.get();
owner.reset();                        // peek now dangles

// 4. Using a moved-from pointer.
auto d = std::make_unique<Widget>();
auto e = std::move(d);
d->update();                          // BUG: d is null now

Using make_unique everywhere prevents the first two entirely. The last two are about lifetime: a raw pointer from get() is a borrow and must not outlive the owner.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. auto a = std::make_unique<int>(5); auto b = a; What happens?

    The copy constructor of unique_ptr is deleted. To transfer ownership, write auto b = std::move(a);.
  2. 2. auto a = std::make_unique<int>(5); auto b = std::move(a); What is the state of a?

    Moving a unique_ptr transfers ownership and leaves the source null, which is safe to test or reassign.
  3. 3. A function only reads a Widget and never stores it. Which parameter type is best?

    Functions that don't take part in ownership shouldn't mention smart pointers. Callers pass *p, and the function works with any Widget, however it's owned.
  4. 4. Why must Shape have a virtual destructor when you store objects in std::vector<std::unique_ptr<Shape>>?

    The default deleter calls delete on a Shape*. Without a virtual destructor, deleting a derived object through a base pointer is undefined behavior.
  5. 5. What does p.release() do?

    release gives up ownership. The caller now must delete the object (or hand it to an owner), otherwise it leaks. reset() is the one that deletes.

Summary

  • std::unique_ptr<T> exclusively owns a heap object and deletes it when it's destroyed. It's as small and fast as a raw pointer.
  • Create one with std::make_unique<T>(args...); use it with *, -> and if (p).
  • It can't be copied, only moved: auto b = std::move(a); leaves a null. Returned locals and temporaries move automatically.
  • Know get() (borrow), reset() (delete and replace), and release() (give up ownership; you must free it).
  • Signatures express ownership: T&/T* to use, unique_ptr<T> by value to take ownership, return unique_ptr<T> from factories.
  • std::vector<std::unique_ptr<Base>> holds polymorphic objects; the base class needs a virtual destructor.
  • Custom deleters turn unique_ptr into an RAII wrapper for C resources; unique_ptr<T[]> calls delete[], but std::vector is usually better.

Next: Smart Pointers: shared_ptr and weak_ptr, for objects that need several owners.