Edit

How to: Create and use unique_ptr instances

A unique_ptr doesn't share its pointer. It can't be copied to another unique_ptr, passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to another unique_ptr and the original unique_ptr no longer owns it. We recommend that you restrict an object to one owner, because multiple ownership adds complexity. When you need a smart pointer for a plain C++ object, use unique_ptr, and when you construct a unique_ptr, use the make_unique helper function.

The following diagram illustrates the transfer of ownership between two unique_ptr instances.

Diagram that shows moving the ownership of a unique pointer.

unique_ptr is defined in the <memory> header in the C++ Standard Library. It's exactly as efficient as a raw pointer and can be used in C++ Standard Library containers. The addition of unique_ptr instances to C++ Standard Library containers is efficient because the move constructor of the unique_ptr eliminates the need for a copy operation.

To use unique_ptr and make_unique, include the <memory> header. The following examples each compile and run as standalone programs.

Example 1

The following example shows how to create unique_ptr instances and pass them between functions. Returning a unique_ptr by value transfers ownership to the caller. Passing a unique_ptr by value to a function transfers ownership to the callee.

// Compile with: cl /EHsc /std:c++17

#include <iostream>
#include <memory>
#include <string>

struct Song {
    std::string artist;
    std::string title;
    Song(const std::string& a, const std::string& t) : artist(a), title(t) {
        std::cout << "Created: " << title << "\n";
    }
    ~Song() { std::cout << "Destroyed: " << title << "\n"; }
};

// Returning a unique_ptr by value transfers ownership to the caller.
std::unique_ptr<Song> SongFactory(const std::string& artist, const std::string& title) {
    return std::make_unique<Song>(artist, title);
}

// Passing a unique_ptr by value transfers ownership to the function.
// The Song is automatically destroyed when the function exits.
void SingSong(std::unique_ptr<Song> song) {
    std::cout << "Singing: " << song->title << " by " << song->artist << "\n";
}

int main() {
    // Create a new unique_ptr with a new object.
    auto song = std::make_unique<Song>("Mr. Children", "Namonaki Uta");
    std::cout << "song points to: " << song->title << "\n";

    // Move ownership from one unique_ptr to another.
    std::unique_ptr<Song> song2 = std::move(song);
    std::cout << "After move, song is " << (song ? "not null" : "null") << "\n";
    std::cout << "song2 points to: " << song2->title << "\n";

    // Obtain unique_ptr from a factory function that returns by value.
    auto song3 = SongFactory("Michael Jackson", "Beat It");

    // Transfer ownership to a function.
    SingSong(std::move(song3));
    std::cout << "After SingSong, song3 is " << (song3 ? "not null" : "null") << "\n";
}
Created: Namonaki Uta
song points to: Namonaki Uta
After move, song is null
song2 points to: Namonaki Uta
Created: Beat It
Singing: Beat It by Michael Jackson
Destroyed: Beat It
After SingSong, song3 is null
Destroyed: Namonaki Uta

These examples demonstrate this basic characteristic of unique_ptr: it can be moved, but not copied. "Moving" transfers ownership to a new unique_ptr and resets the old unique_ptr.

Example 2

The following example shows how to create unique_ptr instances and use them in a vector.

// Compile with: cl /EHsc /std:c++17

#include <iostream>
#include <memory>
#include <string>
#include <vector>

struct Song {
    std::string artist;
    std::string title;
    Song(const std::string& a, const std::string& t) : artist(a), title(t) {}
};

int main() {
    std::vector<std::unique_ptr<Song>> songs;

    // Create unique_ptr<Song> instances and add them to the vector
    // using implicit move semantics.
    songs.push_back(std::make_unique<Song>("B'z", "Juice"));
    songs.push_back(std::make_unique<Song>("Namie Amuro", "Funky Town"));
    songs.push_back(std::make_unique<Song>("Kome Kome Club", "Kimi ga Iru Dake de"));
    songs.push_back(std::make_unique<Song>("Ayumi Hamasaki", "Poker Face"));

    // Pass by const reference to avoid copying.
    // Passing by value causes a compile error because
    // the unique_ptr copy constructor is deleted.
    for (const auto& song : songs) {
        std::cout << "Artist: " << song->artist
                  << "   Title: " << song->title << "\n";
    }
    // The unique_ptr instances in the vector are automatically destroyed when the vector goes out of scope at the end of main()
}
Artist: B'z   Title: Juice
Artist: Namie Amuro   Title: Funky Town
Artist: Kome Kome Club   Title: Kimi ga Iru Dake de
Artist: Ayumi Hamasaki   Title: Poker Face
Destroyed: Juice
Destroyed: Funky Town
Destroyed: Kimi ga Iru Dake de
Destroyed: Poker Face

In the range for loop, notice that the unique_ptr is passed by reference. If you try to pass by value here, the compiler reports an error because the unique_ptr copy constructor is deleted.

Example 3

The following example shows how to initialize a unique_ptr that is a class member.

// Compile with: cl /EHsc /std:c++17

#include <iostream>
#include <memory>

class Engine {
public:
    Engine() { std::cout << "Engine created\n"; }
    ~Engine() { std::cout << "Engine destroyed\n"; }
    void Run() { std::cout << "Engine running\n"; }
};

class Car {
private:
    // Car owns the unique_ptr.
    std::unique_ptr<Engine> engine;
public:
    // Initialize by using make_unique in the member initializer list.
    Car() : engine(std::make_unique<Engine>()) {}

    void Start() {
        engine->Run();
    }
};

int main() {
    Car car;
    car.Start();
}
Engine created
Engine running
Engine destroyed

Example 4

You can use make_unique to create a unique_ptr to an array. make_unique<int[]>(5) creates a five element array that is value-initialized to zero. You can't pass individual element values to make_unique, so assign them after creation.

// Compile with: cl /EHsc /std:c++17

#include <iostream>
#include <memory>

int main() {
    // Create a unique_ptr to an array of 5 integers.
    // The elements are value-initialized to 0.
    auto p = std::make_unique<int[]>(5);

    // Assign values to the array elements.
    for (int i = 0; i < 5; ++i) {
        p[i] = i;
        std::cout << p[i] << "\n";
    }
    // The array is automatically deleted when p goes out of scope.
}
0
1
2
3
4

For more examples, see make_unique.

See also

Smart Pointers (Modern C++)
make_unique