Smart Pointers (C++11)

Smart Pointers (C++11) in C++: Manual and is a rented storage unit with a metal key. Keeping track of that key is entirely on you: hand it to a colleague and…

The Analogy: A Key That Returns Itself

Manual new and delete is a rented storage unit with a metal key. Keeping track of that key is entirely on you: hand it to a colleague and you both think you have it, lose it and the unit is rented forever, hand it back twice and the office calls security. Every bug in the dynamic-memory lesson is a story about that key.

A smart pointer is a key that returns itself. It is a small object that holds the address and — because it is an object with a destructor — gives the memory back automatically the moment it goes out of scope. Not when you remember to. Not on the happy path only. On every path: normal returns, early returns, break, and thrown exceptions.

There are two kinds, and the difference is a question about the key, not about the storage:

  • std::unique_ptr is the only key. One owner. When that owner goes, the unit is emptied. You can pass the key along, but then you no longer have it.
  • std::shared_ptr is a key with a tally on the wall. Copy it and the tally goes up; each copy that dies takes the tally down. The last one out clears the unit.

Ninety percent of the time you want unique_ptr, because ninety percent of the time exactly one thing owns a resource. That is not a compromise — unique_ptr is as fast as a raw pointer and the same size, so you are giving up nothing to get correctness.


Syntax or Core Structure

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

struct Session {
    std::string user;
    int id = 0;

    Session(std::string u, int i) : user(std::move(u)), id(i) {
        std::cout << "  open  " << user << "\n";
    }
    ~Session() {
        std::cout << "  close " << user << "\n";
    }
    void greet() const { std::cout << "  hello " << user << " (#" << id << ")\n"; }
};

int main() {
    std::cout << "-- unique_ptr --\n";
    {
        std::unique_ptr<Session> s = std::make_unique<Session>("Ada", 1);

        s->greet();                        // arrow, exactly like a raw pointer
        (*s).greet();                      // star works too
        std::cout << "  id: " << s->id << "\n";

        if (s) {                           // converts to bool
            std::cout << "  holding something\n";
        }
        Session* raw = s.get();            // borrow WITHOUT taking ownership
        raw->greet();
    }                                      // destructor runs here -- no delete

    std::cout << "\n-- moving ownership --\n";
    {
        std::unique_ptr<Session> a = std::make_unique<Session>("Grace", 2);
        std::unique_ptr<Session> b = std::move(a);     // ownership transfers

        std::cout << "  a empty? " << (a ? "no" : "yes") << "\n";
        b->greet();
        b.reset();                         // free it early, explicitly
        std::cout << "  after reset, b empty? " << (b ? "no" : "yes") << "\n";
    }

    std::cout << "\n-- shared_ptr --\n";
    {
        std::shared_ptr<Session> first = std::make_shared<Session>("Alan", 3);
        std::cout << "  count: " << first.use_count() << "\n";      // 1
        {
            std::shared_ptr<Session> second = first;                 // copy is legal
            std::cout << "  count: " << first.use_count() << "\n";  // 2
            second->greet();
        }
        std::cout << "  count: " << first.use_count() << "\n";      // 1
    }                                      // last owner gone -> destroyed

    std::cout << "\n-- an array, and a container --\n";
    {
        std::unique_ptr<int[]> buffer = std::make_unique<int[]>(4);
        buffer[0] = 10;                    // indexable
        std::cout << "  buffer[0] = " << buffer[0] << "\n";

        std::vector<std::unique_ptr<Session>> sessions;
        sessions.push_back(std::make_unique<Session>("Edsger", 4));
        sessions.push_back(std::make_unique<Session>("Barbara", 5));
        for (const auto& s : sessions) s->greet();
    }                                      // both destroyed, in order
}

There is not one delete in that program, and not one leak. Every close line in the output is a destructor firing at a closing brace.


Technical Depth: Choosing, Passing, and the Cycle Problem

The three smart pointers

std::unique_ptrstd::shared_ptrstd::weak_ptr
OwnersExactly oneAny numberNone — observes only
CopyableNoYesYes
MovableYesYesYes
SizeSame as a raw pointerTwo pointersTwo pointers
Runtime costZeroAtomic count on copy/destroyCheap
Frees whenThe owner diesThe last owner diesNever
Use forAlmost everythingGenuinely shared ownershipBreaking cycles, caches

unique_ptr compiles to the same machine code as a raw pointer plus a delete. There is no reason to prefer a raw owning pointer to it, ever.

Always make_unique / make_shared

auto a = std::make_unique<Session>("Ada", 1);          // do this
std::unique_ptr<Session> b(new Session("Ada", 1));     // works, but why

make_unique is shorter, mentions the type once, and is exception-safe in argument lists where a bare new is not. make_shared goes further: it allocates the object and its reference-count block in one allocation instead of two.

The one case you must use the constructor is a custom deleter (below), or when adopting a pointer from a C API.

Passing smart pointers to functions

This is where most confusion lives. The question to ask is: does this function want ownership?

void observe(const Session& s);                    // just reading -- take a reference
void mutate(Session& s);                           // modifying -- reference
void maybe(const Session* s);                      // may be null -- raw pointer
void consume(std::unique_ptr<Session> s);          // TAKES ownership
void share(std::shared_ptr<Session> s);            // shares ownership

Called like this:

auto s = std::make_unique<Session>("Ada", 1);

observe(*s);                        // dereference
maybe(s.get());                     // borrow the address
consume(std::move(s));              // hand it over -- s is empty afterwards

Do not take const std::unique_ptr<T>&. It says "I need to know about your ownership but I will not touch it", which is almost never true. If the function only uses the object, take T& or const T& and let the caller dereference. That way the function works with stack objects, shared_ptrs, and references too.

Function needsParameter type
To read the objectconst T&
To modify the objectT&
The object, possibly absentconst T* or T*
To take ownershipstd::unique_ptr<T> by value
To keep a co-owning referencestd::shared_ptr<T> by value

unique_ptr moves, it does not copy

auto a = std::make_unique<int>(1);
// auto b = a;                   // ERROR -- deliberately not copyable
auto b = std::move(a);           // fine; a is now nullptr

That compile error is the whole feature. Two owners means two deletes, so the language refuses. After a move, the source is empty and safe to check but not to dereference.

Returning one from a function needs no std::move:

std::unique_ptr<Session> openSession(const std::string& user) {
    return std::make_unique<Session>(user, 1);     // moved automatically
}

The factory pattern, and polymorphism

unique_ptr is how you return polymorphic objects — the case where you genuinely need the heap:

class Shape {
public:
    virtual ~Shape() = default;                     // still essential
    virtual double area() const = 0;
};

class Circle : public Shape {
public:
    explicit Circle(double r) : radius(r) {}
    double area() const override { return 3.14159 * radius * radius; }
private:
    double radius;
};

std::unique_ptr<Shape> makeShape(const std::string& kind) {
    if (kind == "circle") return std::make_unique<Circle>(2.0);
    return nullptr;
}

std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(1.0));
for (const auto& s : shapes) std::cout << s->area() << "\n";

Note that unique_ptr does not excuse you from a virtual destructor. Deleting a Circle through a Shape* without one is still undefined behaviour; the smart pointer calls delete, it does not fix what delete does.

When shared_ptr is right, and what it costs

Use it when ownership is genuinely joint and you cannot say which owner outlives the others — a cache handing out entries, a node in a graph reachable from several places, an object captured by an asynchronous callback.

auto config = std::make_shared<Config>();
worker1.setConfig(config);                 // both keep it alive
worker2.setConfig(config);

The cost is real: every copy and destruction touches an atomic counter, which is slower than nothing and can contend across threads. And a shared_ptr is twice the size of a raw pointer. Reach for it because you need shared ownership, not because it feels safer.

One subtlety: the count is thread-safe, the object is not. Two threads may copy the same shared_ptr freely; if they both write to what it points at, you still need a mutex.

The reference cycle, and weak_ptr

shared_ptr has one failure mode, and it is a leak:

struct Node {
    std::shared_ptr<Node> next;
    std::shared_ptr<Node> prev;               // BUG waiting to happen
};

auto a = std::make_shared<Node>();
auto b = std::make_shared<Node>();
a->next = b;
b->prev = a;                                  // a and b now hold each other
// both go out of scope -- neither count reaches 0 -- both leak

Each keeps the other's count at 1. Reference counting cannot see the cycle. The fix is to make one direction non-owning:

struct Node {
    std::shared_ptr<Node> next;               // owns forward
    std::weak_ptr<Node> prev;                 // observes backward
};

A weak_ptr does not keep the object alive and cannot be dereferenced directly. You must lock() it, which gives you a shared_ptr that is empty if the object is gone:

if (std::shared_ptr<Node> parent = node->prev.lock()) {
    parent->doSomething();                    // safe -- alive for this block
} else {
    std::cout << "parent already destroyed\n";
}

The rule of thumb: ownership points one way. Parent owns child with shared_ptr; child refers back with weak_ptr.

Custom deleters

Not every resource is freed with delete. A unique_ptr can own anything that has a release function:

#include <cstdio>

auto closeFile = [](std::FILE* f) { if (f) std::fclose(f); };
std::unique_ptr<std::FILE, decltype(closeFile)> file(std::fopen("data.txt", "r"),
                                                     closeFile);
if (file) {
    // use file.get() with the C API; fclose happens automatically
}

That turns any C handle — a socket, a database connection, a window — into an RAII object without writing a wrapper class.

What you still do not need a smart pointer for

std::vector<int> v(1000);            // already heap-allocated and self-freeing
std::string s = "text";              // same
Session s("Ada", 1);                 // a plain stack object is best of all

Smart pointers manage heap objects. Containers already do that internally. The priority order is: stack object, then container, then unique_ptr, then shared_ptr, and raw new essentially never.


Real World Example: A Document Editor with Shared Assets

This example needs all three smart pointers, each for a different reason — which is the point. A document owns its pages exclusively, pages share images with each other (the same photo may appear on several pages, and it should be loaded once), and each page keeps a back-reference to its document without owning it.

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

class Image {
public:
    Image(std::string path, std::size_t kb) : file(std::move(path)), sizeKb(kb) {
        std::cout << "  [load  " << file << " (" << sizeKb << " kB)]\n";
    }
    ~Image() {
        std::cout << "  [free  " << file << "]\n";
    }
    const std::string& name() const { return file; }
    std::size_t kilobytes() const { return sizeKb; }

private:
    std::string file;
    std::size_t sizeKb;
};

class Document;                                        // forward declaration

class Page {
public:
    Page(int pageNumber, std::weak_ptr<Document> owner)
        : number(pageNumber), document(std::move(owner)) {}

    void addImage(std::shared_ptr<Image> image) {
        images.push_back(std::move(image));            // co-owns it
    }

    std::size_t weightKb() const {
        std::size_t total = 0;
        for (const std::shared_ptr<Image>& img : images) {
            total += img->kilobytes();
        }
        return total;
    }

    int pageNumber() const { return number; }
    std::size_t imageCount() const { return images.size(); }

    void describe() const;                             // defined after Document

private:
    int number;
    std::weak_ptr<Document> document;                  // does NOT own upward
    std::vector<std::shared_ptr<Image>> images;        // shares sideways
};

class Document : public std::enable_shared_from_this<Document> {
public:
    explicit Document(std::string documentTitle) : title(std::move(documentTitle)) {}

    Page& addPage() {
        int next = static_cast<int>(pages.size()) + 1;
        pages.push_back(std::make_unique<Page>(next, weak_from_this()));
        return *pages.back();                          // exclusive ownership stays here
    }

    // Loads each distinct file once and hands out co-owning handles.
    std::shared_ptr<Image> image(const std::string& path, std::size_t kb) {
        auto it = cache.find(path);
        if (it != cache.end()) {
            if (std::shared_ptr<Image> alive = it->second.lock()) {
                std::cout << "  [reuse " << path << "]\n";
                return alive;
            }
        }
        std::shared_ptr<Image> loaded = std::make_shared<Image>(path, kb);
        cache[path] = loaded;                           // cache observes, never owns
        return loaded;
    }

    const std::string& name() const { return title; }
    std::size_t pageCount() const { return pages.size(); }

    std::size_t totalKb() const {
        std::size_t total = 0;
        for (const std::unique_ptr<Page>& p : pages) total += p->weightKb();
        return total;
    }

    void report() const {
        std::cout << "\n" << title << ": " << pages.size() << " pages, "
                  << totalKb() << " kB of images\n";
        for (const std::unique_ptr<Page>& p : pages) p->describe();
    }

private:
    std::string title;
    std::vector<std::unique_ptr<Page>> pages;               // exclusive
    std::map<std::string, std::weak_ptr<Image>> cache;      // non-owning index
};

void Page::describe() const {
    std::cout << "  page " << number << ": " << images.size()
              << " images, " << weightKb() << " kB";
    if (std::shared_ptr<Document> doc = document.lock()) {
        std::cout << " (in \"" << doc->name() << "\")";
    } else {
        std::cout << " (orphaned)";
    }
    std::cout << "\n";
}

int main() {
    std::shared_ptr<Document> doc = std::make_shared<Document>("Annual Report");

    Page& cover = doc->addPage();
    Page& body  = doc->addPage();

    std::shared_ptr<Image> logo = doc->image("logo.png", 40);
    cover.addImage(logo);
    std::cout << "  logo owners: " << logo.use_count() << "\n";

    cover.addImage(doc->image("hero.jpg", 900));
    body.addImage(doc->image("logo.png", 40));         // cache hit -- same object
    std::cout << "  logo owners: " << logo.use_count() << "\n";

    body.addImage(doc->image("chart.svg", 60));

    doc->report();

    std::cout << "\n-- closing document --\n";
    doc.reset();                                        // everything unwinds here
    std::cout << "-- closed --\n";
}

Output:

  [load  logo.png (40 kB)]
  logo owners: 2
  [load  hero.jpg (900 kB)]
  [reuse logo.png]
  logo owners: 3
  [load  chart.svg (60 kB)]

Annual Report: 2 pages, 1040 kB of images
  page 1: 2 images, 940 kB (in "Annual Report")
  page 2: 2 images, 100 kB (in "Annual Report")

-- closing document --
  [free  hero.jpg]
  [free  chart.svg]
  [free  logo.png]
-- closed --

Each pointer choice answers a specific ownership question, and swapping any of them for another breaks something concrete.

Pages are unique_ptr. A page belongs to exactly one document; nothing else may keep it alive, and when the document goes, its pages go. That is textbook exclusive ownership, so std::vector<std::unique_ptr<Page>> is right and shared_ptr would be both slower and a lie about the design. addPage returns Page& rather than a pointer precisely to make that clear: the caller gets to use the page, never to own it.

Images are shared_ptr. logo.png appears on both pages and is loaded once — the output proves it, with one [load logo.png] and one [reuse]. Neither page can be said to own it, and neither can be destroyed first as a matter of policy, so the count decides. Watch use_count go from 2 (the local logo plus page 1) to 3 once page 2 takes a handle — and note it stops there, because the cache holds only a weak_ptr and the temporary returned by image is moved into the page rather than copied. The [free] lines at the end fire exactly when the last owner of each image releases it, which is why logo.png is freed last despite being loaded first.

The upward link and the cache are weak_ptr. These are the two places a shared_ptr would leak. If Page::document were a shared_ptr<Document>, the document would own the page and the page would own the document — the exact cycle from the technical section, and doc.reset() at the end would free nothing at all. Making it weak means ownership points strictly downward. The image cache has the same shape: if it held shared_ptr<Image>, no image would ever be freed while the document lived, because the cache alone would keep every one alive. Holding weak_ptr makes the cache an index rather than an owner — it can find an image that is still in use, and correctly reports a miss for one that has been released. That is what the if (auto alive = it->second.lock()) inside image is testing, and it is why the check is nested inside the find: the key may be present while the object behind it is already gone.

enable_shared_from_this is what makes the weak back-reference possible. Inside addPage, this is a raw Document*, and constructing a shared_ptr from it would create a second, independent count that knows nothing about the first — a double-free in waiting. Deriving from enable_shared_from_this lets weak_from_this() produce a handle tied to the existing control block. This is why doc is a shared_ptr in main and why it is created with make_shared: calling weak_from_this() on a Document that was never owned by a shared_ptr yields an empty pointer, and describe would print (orphaned).

Finally, note that main contains no delete, no try/catch for cleanup, and no destructor of its own — and yet the teardown order in the output is exactly correct. doc.reset() drops the last owner of the document, whose destructor destroys its vector<unique_ptr<Page>>, which destroys each page, which drops its shared_ptr<Image> handles, the last of which frees each image. Had an exception been thrown anywhere in main, the identical sequence would have run.


Common Mistakes

  1. Trying to copy a unique_ptr. It will not compile, by design. Use std::move, or reconsider whether you wanted shared_ptr.
  2. Using a unique_ptr after moving from it. The source is left null; dereferencing it is undefined behaviour.
  3. Two smart pointers from one raw pointer. std::shared_ptr<T> a(raw); std::shared_ptr<T> b(raw); creates two counts and a double free. Never let a raw pointer be adopted twice.
  4. Reference cycles with shared_ptr. Mutual ownership means neither count reaches zero. Make one direction weak_ptr.
  5. Taking const std::unique_ptr<T>& as a parameter. Take const T& and let the caller dereference.
  6. delete on p.get(). The smart pointer will delete it again. Never free what a smart pointer owns.
  7. Storing get() and keeping it. The raw pointer dangles as soon as the owner dies or resets.
  8. Omitting the virtual destructor. A unique_ptr<Base> holding a Derived still needs virtual ~Base().
  9. shared_ptr everywhere out of caution. It costs atomics, doubles the pointer size, and hides the ownership design.
  10. std::shared_ptr<T>(new T) instead of make_shared. Two allocations rather than one, and less exception-safe in argument lists.
  11. Dereferencing a weak_ptr. You cannot; call lock() and check the result.
  12. Wrapping something that already manages itself. std::unique_ptr<std::vector<int>> is nearly always a plain std::vector<int>.

Best Practices

  • Default to std::unique_ptr. Zero overhead, and it documents that ownership is exclusive.
  • Use std::make_unique and std::make_shared, not a bare new.
  • Reach for shared_ptr only for genuinely joint ownership, then use weak_ptr for every back-reference.
  • Let ownership point one way. Owners hold shared_ptr, observers hold weak_ptr or a raw pointer.
  • Pass T& or const T& when a function only uses the object; pass unique_ptr by value only to transfer ownership.
  • Return unique_ptr from factory functions. No std::move needed on the return.
  • Keep a virtual destructor on any polymorphic base, smart pointer or not.
  • Never mix raw and smart ownership for the same object. One owner, one mechanism.
  • Use a custom deleter to bring C handles under RAII instead of writing a wrapper class.
  • Prefer a stack object or a container first. Smart pointers are for heap objects that genuinely need to be on the heap.

Practice Exercises

  1. Write a class that prints in both its constructor and destructor. Create one with std::make_unique inside a block, move it to a second unique_ptr, print whether the first is now empty, and observe exactly where the destructor message appears.
  2. Write std::unique_ptr<Shape> makeShape(const std::string& kind) returning a Circle, a Square or nullptr. Store several in a std::vector<std::unique_ptr<Shape>> and total their areas. Then remove virtual from the base destructor and describe what changes.
  3. Build the two-node reference cycle from this lesson with shared_ptr in both directions and confirm, with destructor messages, that neither node is freed. Fix it with weak_ptr and confirm both are.
  4. Write a Registry class holding std::map<std::string, std::weak_ptr<Session>>. Add a find that returns std::shared_ptr<Session> — empty if the session has expired. Demonstrate a hit and an expired miss, and explain why a map of shared_ptr would never report a miss.