Skip to main content

Lesson 3 of 7

unique_ptr - Sole Ownership

`std::unique_ptr<T>` is a **zero-overhead smart pointer** that owns heap memory and automatically frees it when it goes out of scope (or is reset). It enforces **sole ownership** - it cannot be copied (copy constructor = deleted), only moved. This makes the ownership model explicit: exactly one `unique_ptr` owns each resource. Use `std::make_unique<T>()` (C++14) - never construct `unique_ptr` from a raw pointer from `new`.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

unique_ptr - Ownership Transfer, Custom Deleters & Patterns

unique_ptr - Ownership Transfer, Custom Deleters & Patterns
#include <iostream>
#include <memory>
#include <fstream>
#include <functional>

class Resource {
    int id_;
public:
    explicit Resource(int id) : id_(id) {
        std::cout << "Resource " << id_ << " created
";
    }
    ~Resource() { std::cout << "Resource " << id_ << " destroyed
"; }
    int id() const { return id_; }
    void use() { std::cout << "Using resource " << id_ << "
"; }
};

// ── make_unique - preferred (no raw new) ─────────────────────
void basic_unique_ptr() {
    auto p = std::make_unique<Resource>(1);   // allocated & owned
    p->use();                                  // -> dereferences
    (*p).use();                                // same thing
    std::cout << "id=" << p->id() << "
";

    // Automatically freed here when p goes out of scope
}

// ── Ownership transfer - move, not copy ──────────────────────
void transfer_demo() {
    auto p1 = std::make_unique<Resource>(2);

    // auto p2 = p1;     ← COMPILE ERROR: copy deleted
    auto p2 = std::move(p1);  // transfer ownership to p2
    // p1 is now EMPTY (nullptr)
    if (!p1) std::cout << "p1 is empty after move
";

    p2->use();   // p2 owns the Resource
    // p2 destroys Resource 2 on scope exit
}

// ── Functions taking unique_ptr ───────────────────────────────
// Takes ownership (caller gives up resource)
void consume(std::unique_ptr<Resource> res) {
    res->use();
}  // res destroyed here

// Observes without taking ownership
void observe(const Resource* res) {  // raw pointer for observation is fine
    res->use();
}

// ── Custom deleter ────────────────────────────────────────────
// For resources not freed with delete (e.g., FILE*, C handles)
void custom_deleter_demo() {
    auto file_deleter = [](FILE* f) {
        if (f) { std::cout << "Closing file
"; fclose(f); }
    };
    std::unique_ptr<FILE, decltype(file_deleter)>
        fp(fopen("test_unique.txt", "w"), file_deleter);
    if (fp) {
        fputs("hello
", fp.get());   // .get() returns raw pointer
    }
    // file automatically closed when fp goes out of scope
}

// ── unique_ptr in containers ──────────────────────────────────
#include <vector>
void container_demo() {
    std::vector<std::unique_ptr<Resource>> resources;
    for (int i = 3; i <= 5; ++i) {
        resources.push_back(std::make_unique<Resource>(i));
    }
    // All Resources destroyed in reverse order when vector goes out of scope
}

int main() {
    std::cout << "--- basic ---
";
    basic_unique_ptr();

    std::cout << "
--- transfer ---
";
    transfer_demo();

    std::cout << "
--- consume ---
";
    auto r = std::make_unique<Resource>(6);
    observe(r.get());           // pass raw pointer - r still owns
    consume(std::move(r));      // r gives up ownership
    if (!r) std::cout << "r is empty after consume
";

    std::cout << "
--- custom deleter ---
";
    custom_deleter_demo();

    std::cout << "
--- container ---
";
    container_demo();

    return 0;
}

Common Mistakes

  • `p.get()` gives raw pointer - that raw pointer carries no ownership. Never store it in another `unique_ptr` or delete it independently. Use `.get()` only to pass to legacy APIs that need a raw pointer.
  • Returning `unique_ptr` from a factory is always correct - `std::unique_ptr<T> make_thing()` - the compiler applies copy elision (NRVO) or move, so no copy is made. This is the canonical factory function pattern.
  • Passing `unique_ptr` by value when observation is all you need - if a function just needs to read the object, pass `const T&` or `const T*` (via `.get()`). Passing `unique_ptr` by value transfers ownership - only do this intentionally.

Tip

Tip

Practice uniqueptr Sole Ownership in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Exclusive ownership smart pointer with zero overhead and move semantics

Practice Task

Note

Practice Task - (1) Write a working example of uniqueptr Sole Ownership from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with uniqueptr Sole Ownership is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • `std::unique_ptr<T>` is a **zero-overhead smart pointer** that owns heap memory and automatically frees it when it goes out of scope (or is reset).
  • `p.get()` gives raw pointer - that raw pointer carries no ownership. Never store it in another `unique_ptr` or delete it independently. Use `.get()` only to pass to legacy APIs that need a raw pointer.
  • Returning `unique_ptr` from a factory is always correct - `std::unique_ptr<T> make_thing()` - the compiler applies copy elision (NRVO) or move, so no copy is made. This is the canonical factory function pattern.
  • Passing `unique_ptr` by value when observation is all you need - if a function just needs to read the object, pass `const T&` or `const T*` (via `.get()`). Passing `unique_ptr` by value transfers ownership - only do this intentionally.

Topics in This Module

0/7 done