Chapter 43 of 48

Smart Pointers

In Dynamic Memory Allocation we met the three classic bugs of manual memory management: memory leaks (forgetting delete), dangling pointers (using memory after delete) and double delete. In Exception Handling we saw a fourth: an exception can jump over your delete entirely.

Modern C++ solves all of these with smart pointers: small class objects that hold a pointer and automatically delete the object at the right time. With smart pointers, you will almost never write delete again. The C++ Core Guidelines go further and say a raw pointer (T*) should never own memory. This chapter covers the three smart pointers in <memory>: std::unique_ptr, std::shared_ptr and std::weak_ptr, all from C++11.


The Idea Behind Smart Pointers: RAII

RAII (Resource Acquisition Is Initialization) means tying a resource (memory, a file, a lock, a socket) to the lifetime of an object: the constructor acquires the resource and the destructor releases it. Because C++ guarantees that destructors of local objects run when the scope ends (normally or through an exception), the resource can never be forgotten.

You already use RAII every day: a std::vector frees its buffer in its destructor, and a std::string does the same. A smart pointer applies the same idea to a single object created with new.

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

class Report {
    std::string name;
public:
    explicit Report(std::string n) : name(n) { std::cout << "  open  " << name << '\n'; }
    ~Report() { std::cout << "  close " << name << '\n'; }
};

void rawVersion() {
    Report* r = new Report("raw");
    throw std::runtime_error("disk full");   // delete below is never reached
    delete r;
}

void smartVersion() {
    std::unique_ptr<Report> r = std::make_unique<Report>("smart");
    throw std::runtime_error("disk full");   // r's destructor still runs during unwinding
}

int main() {
    std::cout << "Raw pointer:\n";
    try { rawVersion(); } catch (const std::exception& e) { std::cout << "  caught: " << e.what() << '\n'; }

    std::cout << "Smart pointer:\n";
    try { smartVersion(); } catch (const std::exception& e) { std::cout << "  caught: " << e.what() << '\n'; }
}

Output:

Raw pointer:
  open  raw
  caught: disk full
Smart pointer:
  open  smart
  close smart
  caught: disk full

In the raw version, "close raw" never appears. The exception left the function before delete r; ran, so the Report object (and anything it owned) leaked. In the smart version, stack unwinding destroyed the local unique_ptr, and its destructor deleted the Report. No try/catch/delete juggling was needed.


The Three Smart Pointers at a Glance

std::unique_ptr<T>std::shared_ptr<T>std::weak_ptr<T>
OwnershipExclusive: exactly one ownerShared: many owners, reference countedNone: observes a shared_ptr-managed object
Copyable?No (move only)Yes (copy increments count)Yes
Deletes the object whenThe owner is destroyed or resetThe last owner is destroyed or resetNever
Size (typical 64-bit)Same as a raw pointer (8 bytes)Two pointers (16 bytes)Two pointers (16 bytes)
OverheadNoneControl block + atomic count updatesSame control block
Create withstd::make_unique (C++14)std::make_shared (C++11)From a shared_ptr

Default choice: use unique_ptr. Switch to shared_ptr only when ownership is genuinely shared, meaning there is no single object that clearly should be responsible for the lifetime.


std::unique_ptr: Exclusive Ownership

A unique_ptr is the sole owner of an object. When the unique_ptr is destroyed, it deletes the object. Since two owners would both try to delete, copying is disabled (its copy constructor and copy assignment are deleted). Ownership can, however, be transferred with std::move. (We study exactly what std::move does in the next chapter, Move Semantics & Rvalue References; for now, read it as "hand over ownership".)

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

struct Book {
    std::string title;
    int pages;
    Book(std::string t, int p) : title(t), pages(p) { std::cout << "Book(" << title << ")\n"; }
    ~Book() { std::cout << "~Book(" << title << ")\n"; }
};

int main() {
    auto b1 = std::make_unique<Book>("C++ Primer", 970);   // C++14
    std::cout << b1->title << " has " << (*b1).pages << " pages\n";

    // std::unique_ptr<Book> copy = b1;            // error: copy constructor is deleted
    std::unique_ptr<Book> b2 = std::move(b1);      // ownership moves to b2
    std::cout << std::boolalpha << "b1 empty? " << (b1 == nullptr) << '\n';
    std::cout << "b2 owns: " << b2->title << '\n';

    Book* observer = b2.get();                     // non-owning raw pointer
    std::cout << "via get(): " << observer->pages << '\n';

    b2.reset(new Book("CLRS", 1312));              // deletes the old Book, owns the new one
    std::cout << "after reset: " << b2->title << '\n';

    Book* raw = b2.release();                      // gives up ownership WITHOUT deleting
    std::cout << "released, b2 empty? " << !b2 << '\n';
    delete raw;                                    // now we must delete it ourselves

    std::cout << "end of main\n";
}

Output:

Book(C++ Primer)
C++ Primer has 970 pages
b1 empty? true
b2 owns: C++ Primer
via get(): 970
Book(CLRS)
~Book(C++ Primer)
after reset: CLRS
released, b2 empty? true
~Book(CLRS)
end of main

Walk through it step by step:

  1. std::make_unique<Book>(...) forwards its arguments to Book's constructor and returns a unique_ptr<Book>. Use -> and * exactly like a raw pointer.

  2. After std::move(b1), b2 owns the book and b1 is guaranteed to be nullptr. Only one owner ever exists.

  3. get() returns the raw pointer without giving up ownership. Use it to call functions that just need to look at the object, never to delete it.

  4. reset(p) deletes the current object and takes ownership of p. Note the order in the output: new Book("CLRS", ...) is evaluated first (as the argument), then the old book is destroyed. reset() with no argument just deletes and becomes empty.

  5. release() gives up ownership and returns the raw pointer without deleting. Now you are responsible again. It is rarely needed, mainly for passing ownership to old C-style APIs.

  6. A unique_ptr converts to bool in conditions: true when it owns something.

Why make_unique Instead of new?

  • No naked new in your code, so every allocation is visibly owned.

  • You do not repeat the type: auto p = std::make_unique<Book>(...) vs std::unique_ptr<Book> p(new Book(...)).

  • Before C++17, a call like f(std::unique_ptr<A>(new A), g()) could leak if the compiler ran new A, then g(), and g() threw before the unique_ptr was constructed. C++17 tightened the evaluation-order rules so this particular leak can no longer happen, but make_unique was safe all along.

unique_ptr with Polymorphism and Factories

A unique_ptr<Derived> converts automatically to a unique_ptr<Base>, which makes it perfect for factories and containers of polymorphic objects (from Polymorphism & Virtual Functions):

#include <iostream>
#include <memory>
#include <utility>
#include <vector>

class Shape {
public:
    virtual ~Shape() = default;               // essential when deleting through Shape*
    virtual double area() const = 0;
    virtual const char* name() const = 0;
};

class Circle : public Shape {
    double r;
public:
    explicit Circle(double radius) : r(radius) {}
    ~Circle() override { std::cout << "~Circle\n"; }
    double area() const override { return 3.14159 * r * r; }
    const char* name() const override { return "Circle"; }
};

class Square : public Shape {
    double s;
public:
    explicit Square(double side) : s(side) {}
    ~Square() override { std::cout << "~Square\n"; }
    double area() const override { return s * s; }
    const char* name() const override { return "Square"; }
};

// Factory: returns ownership to the caller
std::unique_ptr<Shape> makeShape(char kind, double size) {
    if (kind == 'c') return std::make_unique<Circle>(size);
    return std::make_unique<Square>(size);
}

// Only looks at the shape: takes a reference, not a smart pointer
void print(const Shape& s) {
    std::cout << s.name() << " area = " << s.area() << '\n';
}

// Takes ownership: "sink" parameter by value
void consume(std::unique_ptr<Shape> s) {
    std::cout << "consuming a " << s->name() << '\n';
}   // s is destroyed here

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(makeShape('c', 1.0));
    shapes.push_back(makeShape('s', 2.0));
    shapes.push_back(std::make_unique<Circle>(2.0));

    for (const auto& s : shapes) print(*s);

    consume(std::move(shapes.back()));   // the vector's last slot is now nullptr
    shapes.pop_back();
    std::cout << "leaving main\n";
}   // the vector is destroyed and each unique_ptr deletes its shape

Output:

Circle area = 3.14159
Square area = 4
Circle area = 12.5664
consuming a Circle
~Circle
leaving main
~Circle
~Square

This small program shows the standard ownership conventions for function parameters, recommended by the C++ Core Guidelines:

Parameter typeMeaning
const Shape& or Shape*"I only use the object; I don't care how it is owned." (Most functions should look like this.)
std::unique_ptr<Shape> by value"I take ownership." The caller must write std::move, making the transfer visible.
std::unique_ptr<Shape>&"I may reset or replace your pointer." Rare.
Return std::unique_ptr<Shape>"You now own what I created." (Factories.)

One important warning: unique_ptr<Shape> calls delete on a Shape*. If Shape did not have a virtual destructor, deleting a Circle through it would be undefined behaviour, exactly as with raw pointers in Polymorphism & Virtual Functions. Smart pointers do not remove that rule.

Arrays and Custom Deleters

std::unique_ptr<T[]> is a specialization for arrays: it calls delete[] and offers operator[] instead of ->. For resources that are not freed with delete at all, such as a C FILE* that must be closed with fclose, you can supply a custom deleter as the second template argument.

#include <cstdio>
#include <iostream>
#include <memory>

int main() {
    // Array form: uses delete[] and provides operator[]
    std::unique_ptr<int[]> marks = std::make_unique<int[]>(5);   // 5 ints, value-initialized to 0
    for (int i = 0; i < 5; ++i) marks[i] = (i + 1) * 10;
    std::cout << "marks[4] = " << marks[4] << '\n';

    // Custom deleter: close a C FILE* automatically
    auto closer = [](std::FILE* f) {
        std::cout << "fclose called\n";
        std::fclose(f);
    };
    {
        std::unique_ptr<std::FILE, decltype(closer)> file(std::fopen("demo.txt", "w"), closer);
        if (file) std::fputs("written through a smart pointer\n", file.get());
    }   // closer runs here

    std::cout << "sizeof(int*)                 = " << sizeof(int*) << '\n';
    std::cout << "sizeof(unique_ptr<int>)      = " << sizeof(std::unique_ptr<int>) << '\n';
    std::cout << "sizeof(unique_ptr<FILE, fn>) = " << sizeof(std::unique_ptr<std::FILE, int (*)(std::FILE*)>) << '\n';
    std::cout << "sizeof(shared_ptr<int>)      = " << sizeof(std::shared_ptr<int>) << '\n';
}

Output (GCC 15, x86-64):

marks[4] = 50
fclose called
sizeof(int*)                 = 8
sizeof(unique_ptr<int>)      = 8
sizeof(unique_ptr<FILE, fn>) = 16
sizeof(shared_ptr<int>)      = 16

A unique_ptr with the default deleter (or any empty deleter like a captureless lambda) is exactly the size of a raw pointer: truly zero overhead. A deleter that has state, such as a function pointer, must be stored inside, which increases the size. In practice, prefer std::vector over unique_ptr<T[]> for arrays; the array form is useful when you need a fixed buffer with no size or capacity bookkeeping. (C++20 also adds std::make_unique_for_overwrite, which skips zero-initialization for buffers you will fill anyway.)


std::shared_ptr: Shared Ownership

Sometimes several objects really need to keep the same object alive: a configuration used by many services, a node in a graph with several parents, a cached image shown in multiple windows. A shared_ptr allows copies; all copies share ownership, and the object is deleted when the last owner goes away.

It does this with a control block, a separate small structure that holds the strong count (number of shared_ptr owners), the weak count (number of weak_ptr observers) and the deleter.

auto p = std::make_shared<Config>("fast");   auto q = p;

  p ──────┐                       make_shared puts the control block and
          ▼                       the object in ONE allocation:
  q ──► ┌──────────────────────┬──────────────────┐
        │ control block        │ Config object    │
        │ strong count = 2     │ mode = "fast"    │
        │ weak count   = 0     │                  │
        └──────────────────────┴──────────────────┘
Each shared_ptr holds two pointers: one to the object, one to the control block.
Copy  → strong count + 1          Destroy/reset → strong count − 1
strong count reaches 0 → object destroyed
strong and weak counts both 0 → control block freed
#include <iostream>
#include <memory>
#include <string>

struct Config {
    std::string mode;
    explicit Config(std::string m) : mode(m) { std::cout << "Config created\n"; }
    ~Config() { std::cout << "Config destroyed\n"; }
};

class Service {
    std::shared_ptr<Config> cfg;     // each service co-owns the config
    std::string name;
public:
    Service(std::string n, std::shared_ptr<Config> c) : cfg(c), name(n) {}
    void show() const { std::cout << name << " uses mode " << cfg->mode << '\n'; }
};

int main() {
    auto cfg = std::make_shared<Config>("fast");
    std::cout << "owners: " << cfg.use_count() << '\n';

    {
        Service a("Login", cfg);
        Service b("Search", cfg);
        std::cout << "owners: " << cfg.use_count() << '\n';
        a.show();
        b.show();
    }   // a and b destroyed: count goes back down
    std::cout << "owners: " << cfg.use_count() << '\n';

    std::shared_ptr<Config> other = cfg;   // copying is allowed
    cfg.reset();                           // cfg gives up its share
    std::cout << "owners after reset: " << other.use_count() << '\n';
    std::cout << "about to reset the last owner\n";
    other.reset();                         // count hits 0: Config is destroyed now
    std::cout << "end of main\n";
}

Output:

Config created
owners: 1
owners: 3
Login uses mode fast
Search uses mode fast
owners: 1
owners after reset: 1
about to reset the last owner
Config destroyed
end of main

use_count() shows the strong count. It went 1 → 3 when two services copied the pointer, back to 1 when they were destroyed, and the Config was destroyed exactly when the last owner (other) released it, not earlier and not later. Note that use_count() is useful for learning and debugging, but in multithreaded programs its value may already be stale when you read it, so do not base program logic on it.

Facts About shared_ptr Worth Knowing

  • Prefer make_shared. std::shared_ptr<T>(new T(...)) needs two allocations (object, then control block). make_shared does one, which is faster and more cache friendly. One trade-off: with make_shared, the object's memory is freed only when the control block is, so long-lived weak_ptrs keep that whole block allocated (the object's destructor still runs on time).

  • Thread safety. Updating the reference count is atomic, so different threads may copy and destroy their own shared_ptr copies safely. The pointed-to object is not protected; concurrent access to it still needs synchronization. Atomic counting is also the main runtime cost of shared_ptr: pass it by const& (or pass the object by reference) when you do not need a new owner.

  • The deleter is remembered. std::shared_ptr<Base> p = std::make_shared<Derived>(); destroys the object as a Derived even if Base lacks a virtual destructor, because the control block remembers the real type. This is a known difference from unique_ptr, but do not rely on it; give polymorphic bases a virtual destructor anyway.

  • Arrays: std::shared_ptr<T[]> is supported since C++17, and std::make_shared<T[]>(n) since C++20.

  • A unique_ptr can be converted to a shared_ptr (std::shared_ptr<T> s = std::move(u);), but not the other way. Another reason to return unique_ptr from factories: the caller can still choose shared ownership.


The Cycle Problem and std::weak_ptr

Reference counting has one famous weakness: cycles. If A owns B and B owns A, neither count can ever reach zero.

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

struct Person {
    std::string name;
    std::shared_ptr<Person> partner;     // strong reference
    explicit Person(std::string n) : name(n) {}
    ~Person() { std::cout << "~Person(" << name << ")\n"; }
};

int main() {
    {
        auto a = std::make_shared<Person>("Arjun");
        auto b = std::make_shared<Person>("Bela");
        a->partner = b;
        b->partner = a;                  // cycle: each keeps the other alive
        std::cout << "a count = " << a.use_count() << ", b count = " << b.use_count() << '\n';
    }
    std::cout << "end of scope, no destructor ran\n";
}

Output:

a count = 2, b count = 2
end of scope, no destructor ran

When the local a and b went out of scope, each count dropped from 2 to 1, not to 0, because each person's partner member still owned the other. Both objects leaked. LeakSanitizer (part of -fsanitize=address) reports it at exit (trimmed):

Indirect leak of 64 byte(s) in 1 object(s) allocated from:
Indirect leak of 64 byte(s) in 1 object(s) allocated from:
SUMMARY: AddressSanitizer: 128 byte(s) leaked in 2 allocation(s).
After the locals a and b are gone:

   ┌──────────────────┐  partner (strong)  ┌──────────────────┐
   │ Arjun  count = 1 │ ─────────────────► │ Bela   count = 1 │
   │                  │ ◄───────────────── │                  │
   └──────────────────┘  partner (strong)  └──────────────────┘
   Nothing outside points to them, but neither count can reach 0.

A std::weak_ptr refers to an object managed by shared_ptr without owning it: it does not increase the strong count. To use the object, you call lock(), which returns a shared_ptr (owning, for as long as you hold it) if the object is still alive, or an empty shared_ptr if it has already been destroyed.

Make one direction of the relationship (or both, if neither should own the other) a weak_ptr:

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

struct Person {
    std::string name;
    std::weak_ptr<Person> partner;       // non-owning reference breaks the cycle
    explicit Person(std::string n) : name(n) {}
    ~Person() { std::cout << "~Person(" << name << ")\n"; }

    void greetPartner() const {
        if (auto p = partner.lock())     // lock() gives a shared_ptr, or nullptr if gone
            std::cout << name << " says hi to " << p->name << '\n';
        else
            std::cout << name << " has no partner any more\n";
    }
};

int main() {
    auto a = std::make_shared<Person>("Arjun");
    {
        auto b = std::make_shared<Person>("Bela");
        a->partner = b;
        b->partner = a;
        std::cout << "a count = " << a.use_count() << ", b count = " << b.use_count() << '\n';
        a->greetPartner();
    }   // b's count drops to 0: Bela is destroyed
    std::cout << std::boolalpha << "expired? " << a->partner.expired() << '\n';
    a->greetPartner();
}

Output:

a count = 1, b count = 1
Arjun says hi to Bela
~Person(Bela)
expired? true
Arjun has no partner any more
~Person(Arjun)

Now the counts are 1 each (only the local variables own the objects). When b went out of scope, Bela was destroyed immediately. Arjun's weak_ptr noticed: expired() became true and lock() returned an empty pointer, so we never touched a dead object. Compare this with a raw pointer, which would silently dangle.

Typical uses of weak_ptr:

  • Back-pointers in trees and graphs: a child holds weak_ptr to its parent, the parent holds shared_ptr (or unique_ptr) to children.

  • Observers and callbacks: a subject keeps weak_ptrs to listeners so that it does not keep them alive.

  • Caches: keep weak_ptrs to loaded resources; reuse an entry if lock() succeeds, reload it otherwise.

Always use lock() and check the result. Testing expired() and then calling lock() separately is a race in multithreaded code, because the object can die between the two calls.


The "Two Owners from One Raw Pointer" Bug

Each time you construct a shared_ptr from a raw pointer, it creates a new control block. Two control blocks for one object means two independent counts, and two deletes:

#include <memory>

int main() {
    int* raw = new int(42);
    std::shared_ptr<int> p1(raw);   // control block #1, count 1
    std::shared_ptr<int> p2(raw);   // control block #2, count 1 -- BUG
}   // both counts reach 0: raw is deleted twice

With -fsanitize=address (trimmed):

==4323==ERROR: AddressSanitizer: attempting double-free on 0x786d6b9e0010 in thread T0:

The fix is to create the object with make_shared once and then copy the shared_ptr (auto p2 = p1;). A sneaky version of this bug happens inside member functions: writing std::shared_ptr<Task>(this) creates a second owner of an object that is already owned elsewhere. The standard solution is to inherit from std::enable_shared_from_this and call shared_from_this():

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

class Task;
std::vector<std::shared_ptr<Task>> queue;   // a global list of pending tasks

class Task : public std::enable_shared_from_this<Task> {
public:
    void schedule() {
        // queue.push_back(std::shared_ptr<Task>(this));  // WRONG: a second, separate owner
        queue.push_back(shared_from_this());              // shares the existing ownership
    }
};

int main() {
    auto t = std::make_shared<Task>();
    t->schedule();
    std::cout << "owners: " << t.use_count() << '\n';
}

Output:

owners: 2

shared_from_this() only works if the object is already owned by some shared_ptr; since C++17 it throws std::bad_weak_ptr otherwise (for example, for an object on the stack).


Which Pointer Should I Use?

Do you need a pointer at all?  ── no ──► use a value or a container (vector, string ...)
          │ yes
Does this pointer OWN the object (responsible for deleting it)?
          │
          ├── no  ──► raw pointer T* or reference T& (non-owning observer)
          │           or weak_ptr if the object is managed by shared_ptr
          │           and may die before you
          │
          └── yes ──► is there exactly one owner at a time?
                         ├── yes ──► std::unique_ptr  (the default)
                         └── no  ──► std::shared_ptr  (+ weak_ptr to break cycles)

Remember that the best smart pointer is often no pointer. A std::vector<Student> manages its elements perfectly well; you need unique_ptr mainly for polymorphic objects, objects whose lifetime does not follow a scope, optional large members, and the pimpl idiom.

Also note that std::auto_ptr, the pre-C++11 attempt at a smart pointer, had confusing "copy that actually moves" behaviour. It was deprecated in C++11 and removed in C++17. If you see it in old code or old textbooks, replace it with unique_ptr.


Common Mistakes

1. Creating two smart pointers from the same raw pointer

Leads to double delete, as shown above. Never pass the result of get() to another smart pointer's constructor either.

2. Deleting the pointer returned by get()

delete up.get(); deletes the object while the smart pointer still owns it; the smart pointer will delete it again later.

3. Using shared_ptr everywhere "to be safe"

It costs an extra allocation for the control block (unless make_shared is used), atomic operations on every copy, and it hides who is really responsible for an object. Start with unique_ptr.

4. Forgetting about cycles

Doubly linked lists, parent pointers and mutual references made of shared_ptr leak. Use weak_ptr (or a raw non-owning pointer when the lifetime is guaranteed by design) for the back-reference.

5. Using a unique_ptr after moving from it

After auto b = std::move(a);, a is nullptr. Dereferencing it is undefined behaviour (usually a crash).

6. Mismatched array forms

std::unique_ptr<int> p(new int[10]); calls delete instead of delete[]: undefined behaviour. Use std::unique_ptr<int[]>, or better, std::vector<int>.


Interview / GATE-Style Questions

Q1. Why can't a unique_ptr be copied? How do you transfer ownership?

If it could be copied, two unique_ptrs would own the same object and both would delete it. Its copy constructor and copy assignment are deleted. Ownership is transferred by moving: auto b = std::move(a);, after which a is null. Returning a local unique_ptr from a function also moves it automatically.

Q2. What is the output? auto p = std::make_shared<int>(5); auto q = p; std::weak_ptr<int> w = p; p.reset(); std::cout << q.use_count() << ' ' << w.expired();

1 0. After p.reset() only q owns the integer, so the strong count is 1. A weak_ptr does not count as an owner. The object is still alive, so expired() is false, printed as 0 without std::boolalpha.

Q3. What is a control block, and why is make_shared usually better than shared_ptr<T>(new T)?

The control block is a separately allocated structure holding the strong count, weak count and deleter, shared by all shared_ptr/weak_ptr copies. make_shared allocates the object and control block together in one allocation (faster, better locality); shared_ptr<T>(new T) needs two allocations. The downside is that the memory of a make_shared object is reclaimed only when the last weak_ptr also goes away.

Q4. Two objects hold shared_ptrs to each other. What happens, and how do you fix it?

A reference cycle: when outside owners disappear, each strong count stays at 1, so neither destructor runs and both objects leak. Fix it by making at least one link a std::weak_ptr, which does not contribute to the strong count, and use lock() to access the object.

Q5. What is sizeof(std::unique_ptr<int>) compared to sizeof(int*)? And for shared_ptr?

With the default deleter, unique_ptr is the same size as a raw pointer (8 bytes on a typical 64-bit system), because the empty deleter takes no space. shared_ptr is typically twice that (16 bytes): one pointer to the object and one to the control block.

Q6. What is RAII and how do smart pointers use it?

Resource Acquisition Is Initialization: a resource's lifetime is bound to an object; the constructor acquires it and the destructor releases it. Since destructors of local objects always run when their scope ends, including during exception unwinding, the resource is never leaked. A smart pointer acquires ownership of heap memory when constructed and deletes it in its destructor.


Summary

  • Smart pointers apply RAII to heap objects: the destructor deletes the object, even when exceptions occur.

  • unique_ptr: one owner, move-only, zero overhead; create with make_unique (C++14). The default choice.

  • shared_ptr: reference-counted shared ownership via a control block; create with make_shared; the object dies when the last owner goes away.

  • weak_ptr: non-owning observer of a shared_ptr object; breaks cycles; access through lock().

  • Never create two owners from one raw pointer; use enable_shared_from_this to get a shared_ptr to this.

  • Functions that only use an object should take T& or T*, not a smart pointer. Take unique_ptr by value to accept ownership.

  • auto_ptr was removed in C++17.

We used std::move several times in this chapter without fully explaining it. In the next chapter, Move Semantics & Rvalue References, we see what moving really means, why it makes C++ fast, and how to make your own classes movable.