liveBook · Manning

Std::unique_ptr

As explained in 100 C++ Mistakes and How to Avoid Them

std::unique_ptr is a C++ standard-library smart pointer that provides exclusive ownership of a dynamically allocated object or array and automatically manages its lifetime.

std::unique_ptr is a C++ smart pointer for exclusive ownership of a dynamically allocated object or array. It manages the resource’s lifetime automatically, reducing the need for manual deletion during normal execution and exception handling. section 2.8 section 10.6

A common mistake is to copy a raw owning pointer and delete both copies. The second deletion attempts to destroy the same resource again. Even a Buffer that correctly deletes its own array cannot prevent this error when its owning pointers are managed separately. section 2.8

Listing 2.15 A botched attempt at managing an exclusive resource
struct Buffer {
private:
    int* data;
public:
    Buffer() : data(new int[10]) {}
    ~Buffer() { delete[] data; }
};
 
int main() {
    Buffer* b1 = new Buffer();
    Buffer* b2 = b1;                                         #1
    if (b1)
        delete b1;                                           #2
    if (b2)
        delete b2;                                           #3
    return 0;
}

Both pointers refer to the same Buffer, so deleting each one does not represent two independent cleanups. section 2.8

Listing 2.16 Implementing exclusive ownership using unique_ptr
struct Buffer {
private:
    std::unique_ptr<int[]> data;                            #1
public:
    Buffer() : data(std::make_unique<int[]>(10)) {}         #2
};
 
int main() {
    auto b1 = std::make_unique<Buffer>();                   #3
    auto b2 = std::move(b1);                                #4
    return 0;
}

The revised Buffer stores its array in std::unique_ptr<int[]> and creates it with std::make_unique. No user-written destructor is needed for the array. The outer Buffer is also managed by a unique pointer. section 2.8

Use std::move to transfer ownership from one unique pointer to another, as in the revised Buffer example. The source is left empty after the transfer; the resource is not shared. Prefer std::make_unique to writing new directly when creating the owned object or array. section 2.8

Choose std::shared_ptr when multiple owners really need to share a resource. Shared ownership maintains a reference count and has additional size and runtime costs, so prefer unique ownership when sharing is unnecessary. section 2.9

In legacy code, replace raw owning pointers or std::auto_ptr with modern smart pointers where possible. If modern C++ is unavailable, Boost provides boost::scoped_ptr for exclusive ownership. Unlike std::unique_ptr, it does not support ownership transfer by assignment. section 10.6

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Works through object and array ownership, automatic cleanup, and ownership transfer with std::move.
Examples
Contrasts a double-deleted raw Buffer with a Buffer using unique pointers for itself and its array.
What you can do after
Apply std::unique_ptr and std::make_unique to manage an exclusive resource and transfer its ownership.
How it connects
Connects exclusive ownership to RAII, move semantics, and shared ownership.

Also explained in

Compare how 2 books explain std::unique_ptr →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.