SyntaxPilot
Courses/C++/Lesson 28

C++ · Lesson 28 of 40 · 11 min

Smart pointers

queued

These are the notes for C++ episode 28. In episode 10 you rented heap memory with new and gave it back with delete: every new needs exactly one delete. In this episode you see how easy that is to get wrong, and you invent pointers that delete themselves: smart pointers, from the <memory> header. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; outputs and error messages are copied from those runs.

All the examples use a small Photo struct whose constructor prints load and whose destructor prints free (episode 13), so you can see when memory is given back:

struct Photo {
    string name;
    Photo(string n) : name(n) { cout << "load " << name << endl; }
    ~Photo() { cout << "free " << name << endl; }
};

The problem: a photo editor that leaks

Photos are big, so each one is loaded on the heap with new. The editor deletes it at the end of edit. But a blurry photo is skipped early, with return:

#include <iostream>
#include <string>
using namespace std;

struct Photo {
    string name;
    Photo(string n) : name(n) { cout << "load " << name << endl; }
    ~Photo() { cout << "free " << name << endl; }
};

void edit(string file, bool blurry) {
    Photo* p = new Photo(file);
    if (blurry) {
        cout << "too blurry, skip" << endl;
        return;                     // leaves early...
    }
    cout << "editing " << p->name << endl;
    delete p;
}

int main() {
    edit("beach.jpg", false);
    edit("blurry.jpg", true);
    cout << "editor closed" << endl;
    return 0;
}

Output:

load beach.jpg
editing beach.jpg
free beach.jpg
load blurry.jpg
too blurry, skip
editor closed

beach.jpg is loaded and freed. blurry.jpg is loaded, and never freed: the early return jumped right over delete p;. That memory stays taken until the program ends. In an app that runs all day and opens thousands of photos, it slowly eats all the memory. That's a memory leak.

The same thing happens with every early exit: a return in the middle, a break out of a loop, an exception thrown between new and delete (episode 31).

Deleting "to be safe" crashes

So delete in more places? Here the editor deletes the photo, and an album that keeps a copy of the same pointer deletes it too:

#include <iostream>
#include <string>
using namespace std;

struct Photo {
    int pixels[1000];                 // a big photo
    string name;
    Photo(string n) : name(n) { cout << "load " << name << endl; }
    ~Photo() { cout << "free " << name << endl; }
};

int main() {
    Photo* p = new Photo("beach.jpg");
    Photo* album = p;                 // the album keeps a copy
    delete p;                         // the editor frees it
    delete album;                     // the album frees it too
    cout << "done" << endl;
    return 0;
}

Output:

load beach.jpg
free beach.jpg
free beach.jpg
double free or corruption (!prev)
Aborted

(This demo's Photo holds a big pixel array, like a real photo.) free beach.jpg is printed twice: the second delete ran the destructor on memory that was already given back. Then the C library notices the same block being freed twice, prints double free or corruption, and kills the program; done is never printed. Deleting the same memory twice (a double delete) is undefined behaviour: depending on the compiler, the flags and the object, it can crash at once, print garbage, run forever, or seem to work. (Using memory after it's freed, a dangling pointer, is the same kind of bug.)

Why both happened: a raw pointer like Photo* says where the memory is, but not who owns it, who is responsible for giving it back. Too few deletes leak; too many crash.

Step 1: RAII, the hotel check-out

Real-life example: a hotel room.

In a hotel In C++
One guest holds the room (one key card) one clear owner of the memory
You check out, however you leave: early, late, in a hurry the owner object goes out of scope at the closing } (normally, by return, by break, or by an exception)
Housekeeping cleans the room automatically the owner's destructor calls delete

So: wrap the raw pointer inside a small object whose destructor deletes it. C++ always runs a local object's destructor when it goes out of scope, on every path. This idea is called RAII (Resource Acquisition Is Initialization: you get the resource when the object is created, and give it back when the object is destroyed). You already use it every day: vector and string free their memory in their destructors. A pointer that does this is a smart pointer.

Step 2: unique_ptr, one owner

unique_ptr<T> owns one object and deletes it in its destructor. Make one with make_unique<T>(constructor arguments). It works like a pointer: p->name, *p.

#include <iostream>
#include <string>
#include <memory>
using namespace std;

struct Photo {
    string name;
    Photo(string n) : name(n) { cout << "load " << name << endl; }
    ~Photo() { cout << "free " << name << endl; }
};

void edit(string file, bool blurry) {
    unique_ptr<Photo> p = make_unique<Photo>(file);
    if (blurry) {
        cout << "too blurry, skip" << endl;
        return;                     // freed anyway
    }
    cout << "editing " << p->name << endl;
}                                   // no delete anywhere

int main() {
    edit("beach.jpg", false);
    edit("blurry.jpg", true);
    cout << "editor closed" << endl;
    return 0;
}

Output:

load beach.jpg
editing beach.jpg
free beach.jpg
load blurry.jpg
too blurry, skip
free blurry.jpg
editor closed

Now blurry.jpg is freed too: the early return left the function, p went out of scope, and its destructor deleted the photo. There is no delete anywhere in the code.

It can't be copied

What about the double delete? Try giving the photo a second owner:

#include <iostream>
#include <string>
#include <memory>
using namespace std;

struct Photo {
    string name;
    Photo(string n) : name(n) { cout << "load " << name << endl; }
    ~Photo() { cout << "free " << name << endl; }
};

int main() {
    auto p = make_unique<Photo>("beach.jpg");
    unique_ptr<Photo> album = p;      // a second owner?
    return 0;
}

g++ says:

main.cpp:14:31: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Photo; _Dp = std::default_delete<Photo>]’

A unique_ptr's copy constructor is deleted (switched off on purpose with = delete). One room, one key card: two owners can't even compile.

But it can be moved

You can hand ownership over with move() (from <utility>, available through <memory>). The new owner gets the object, and the old unique_ptr becomes empty (nullptr), so it won't delete anything:

#include <iostream>
#include <string>
#include <memory>
using namespace std;

struct Photo {
    string name;
    Photo(string n) : name(n) { cout << "load " << name << endl; }
    ~Photo() { cout << "free " << name << endl; }
};

int main() {
    auto p = make_unique<Photo>("beach.jpg");
    unique_ptr<Photo> album = move(p);   // hand it over
    cout << "album has " << album->name << endl;
    if (!p) cout << "p is empty now" << endl;
    cout << "end of main" << endl;
    return 0;
}

Output:

load beach.jpg
album has beach.jpg
p is empty now
end of main
free beach.jpg

free beach.jpg is printed once, after end of main, when album is destroyed. if (!p) checks whether a smart pointer is empty. How move really works is episode 29's story.

Trap: after a move, the old name is empty. Using it compiles, and crashes:

#include <iostream>
#include <string>
#include <memory>
using namespace std;

struct Photo {
    string name;
    Photo(string n) : name(n) { cout << "load " << name << endl; }
    ~Photo() { cout << "free " << name << endl; }
};

int main() {
    auto p = make_unique<Photo>("beach.jpg");
    auto album = move(p);
    cout << "album has " << album->name << endl;
    cout << "p has " << p->name << endl;     // p is empty!
    cout << "end of main" << endl;
    return 0;
}

Output:

load beach.jpg
album has beach.jpg
Segmentation fault

After move(p), use the new owner, or check if (p) first.

Many photos: a vector of unique_ptr

#include <iostream>
#include <string>
#include <memory>
#include <vector>
using namespace std;

struct Photo {
    string name;
    Photo(string n) : name(n) { cout << "load " << name << endl; }
    ~Photo() { cout << "free " << name << endl; }
};

int main() {
    vector<unique_ptr<Photo>> gallery;      // the gallery owns every photo
    gallery.push_back(make_unique<Photo>("beach.jpg"));
    gallery.push_back(make_unique<Photo>("temple.jpg"));
    for (const auto& p : gallery)           // by reference: no copies
        cout << "showing " << p->name << endl;
    cout << "closing gallery" << endl;
    return 0;
}

Output:

load beach.jpg
load temple.jpg
showing beach.jpg
showing temple.jpg
closing gallery
free beach.jpg
free temple.jpg

When the vector is destroyed, it destroys each unique_ptr, and each one frees its photo. Loop by reference (const auto&), because a unique_ptr can't be copied. A function that only looks at a photo should take a plain const Photo&: ownership stays with the gallery.

unique_ptr costs nothing extra over a raw pointer (same size, same speed), so it is the default choice.

Step 3: shared_ptr, many owners

New problem: beach.jpg is in the "Goa trip" album and in "Favourites". Deleting the Favourites album must not delete the photo, because Goa trip still has it. It should be freed only when the last album lets go, like the last person leaving a room switches off the light.

shared_ptr<T> keeps a reference count: how many shared_ptrs own the object. Copying one adds an owner, destroying or reset()ting one removes an owner, and when the count reaches 0 the object is deleted. Make one with make_shared<T>(...); use_count() shows the count.

#include <iostream>
#include <string>
#include <memory>
using namespace std;

struct Photo {
    string name;
    Photo(string n) : name(n) { cout << "load " << name << endl; }
    ~Photo() { cout << "free " << name << endl; }
};

int main() {
    shared_ptr<Photo> trip = make_shared<Photo>("beach.jpg");
    cout << "owners: " << trip.use_count() << endl;
    {
        shared_ptr<Photo> favourites = trip;   // same photo, 2 albums
        cout << "owners: " << trip.use_count() << endl;
    }                                          // favourites deleted
    cout << "owners: " << trip.use_count() << endl;
    trip.reset();                              // the last owner lets go
    cout << "end of main" << endl;
    return 0;
}

Output:

load beach.jpg
owners: 1
owners: 2
owners: 1
free beach.jpg
end of main

Owners: 1, then 2 inside the braces, back to 1 when favourites was destroyed at } (the photo survived), and trip.reset() made it 0, so the photo was freed before end of main.

shared_ptr is a little slower than unique_ptr: it keeps a separate control block with the count, and updates the count safely across threads. make_shared puts the object and the control block in one allocation.

Step 4: the cycle leak, and weak_ptr

New problem: a social app. Asha's friend is Ravi, so Asha holds a shared_ptr to Ravi; Ravi's friend is Asha, so Ravi holds a shared_ptr to Asha. Like two friends who both say "I'll leave when you leave":

#include <iostream>
#include <string>
#include <memory>
using namespace std;

struct Person {
    string name;
    shared_ptr<Person> friend_;
    Person(string n) : name(n) {}
    ~Person() { cout << "free " << name << endl; }
};

int main() {
    auto asha = make_shared<Person>("Asha");
    auto ravi = make_shared<Person>("Ravi");
    asha->friend_ = ravi;
    ravi->friend_ = asha;              // they point at each other
    cout << "Asha owners: " << asha.use_count() << endl;
    cout << "end of main" << endl;
    return 0;
}

Output:

Asha owners: 2
end of main

Neither free is printed: both leaked, even though we never wrote new. At the end of main, the variable asha goes away, but Ravi still owns Asha, so her count stays at 1. And Asha owns Ravi. Each keeps the other alive forever. That's a reference cycle.

Real-life fix: a friend shouldn't keep you alive. Keep their phone number, not their room key. A weak_ptr watches an object owned by shared_ptrs without owning it: it doesn't add to the count. To use it, call lock(): it returns a shared_ptr if the object is still alive, or an empty one if it's gone.

#include <iostream>
#include <string>
#include <memory>
using namespace std;

struct Person {
    string name;
    weak_ptr<Person> friend_;     // watch, don't own
    Person(string n) : name(n) {}
    ~Person() { cout << "free " << name << endl; }
};

int main() {
    auto asha = make_shared<Person>("Asha");
    auto ravi = make_shared<Person>("Ravi");
    asha->friend_ = ravi;
    ravi->friend_ = asha;
    cout << "Asha owners: " << asha.use_count() << endl;
    if (auto f = asha->friend_.lock())   // still alive?
        cout << "Asha's friend: " << f->name << endl;
    cout << "end of main" << endl;
    return 0;
}

Output:

Asha owners: 1
Asha's friend: Ravi
end of main
free Ravi
free Asha

Asha's count is now 1 (only the variable asha), so at the end of main both are freed. Use weak_ptr for back-links (child → parent), friends lists, observers and caches.

Which pointer should you use?

Pointer Owners Use it for
unique_ptr exactly one the default: any heap object with one clear owner (no extra cost)
shared_ptr many, counted when ownership is really shared (a photo in many albums)
weak_ptr none (watches) looking at a shared object without keeping it alive; breaking cycles
raw pointer T* / reference T& none just using an object someone else owns (function parameters)

The modern rule: no naked new and delete in your code. Use make_unique and make_shared. Better still, use a container (vector, string, map) when one fits.

Common mistakes (and the real g++ messages)

Mistake What happens Fix
unique_ptr<Photo> album = p; error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Photo; ...]’ unique_ptr<Photo> album = move(p);
Using p->name after move(p) compiles; p is empty: undefined behaviour, usually a crash use the new owner, or check if (p)
new ... early return ... delete compiles; memory leak make_unique
Deleting the same raw pointer twice compiles; crash (double free or corruption) or worse one owner: a smart pointer
Two shared_ptrs pointing at each other compiles; both leak make one side a weak_ptr
Making two shared_ptrs from the same raw pointer: shared_ptr<Photo> a(raw), b(raw); compiles; two separate counts, double delete create it once with make_shared, then copy the shared_ptr
Forgetting #include <memory> error: ‘unique_ptr’ was not declared in this scope include <memory>

The library and two albums share photos with shared_ptr. Clearing the library and the Favourites album frees only the photos that no album still holds.

#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;

struct Photo {
    string name;
    Photo(string n) : name(n) { cout << "load " << name << endl; }
    ~Photo() { cout << "free " << name << endl; }
};

struct Album {
    string title;
    vector<shared_ptr<Photo>> photos;     // an album shares its photos
};

int main() {
    vector<shared_ptr<Photo>> library;    // every photo on the phone
    library.push_back(make_shared<Photo>("beach.jpg"));
    library.push_back(make_shared<Photo>("temple.jpg"));
    library.push_back(make_shared<Photo>("thali.jpg"));

    Album goa{"Goa trip", {library[0], library[1]}};
    Album fav{"Favourites", {library[0], library[2]}};
    cout << "beach.jpg owners: " << library[0].use_count() << endl;

    library.clear();                      // delete the photos from the library view
    cout << "library cleared" << endl;
    fav.photos.clear();                   // delete the Favourites album
    cout << "favourites cleared" << endl;
    cout << goa.title << " still shows " << goa.photos[0]->name << endl;
    return 0;                             // goa is destroyed: the last photos are freed
}

Output:

load beach.jpg
load temple.jpg
load thali.jpg
beach.jpg owners: 3
library cleared
free thali.jpg
favourites cleared
Goa trip still shows beach.jpg
free beach.jpg
free temple.jpg

thali.jpg was freed as soon as its last owner (Favourites) let go; beach.jpg and temple.jpg lived until the Goa album was destroyed at the end of main.

Practice

  1. Rewrite an old new int[5] / delete[] program with make_unique.
  2. Keep photos in a vector<unique_ptr<Photo>> and print them.
  3. Print use_count() as a shared_ptr is copied into 3 albums and one album lets go.
  4. Build a parent and child: the parent owns the child with a shared_ptr, the child points back with a weak_ptr.
Solutions

1. unique_ptr<int[]> is the array version: it calls delete[] and supports [].

#include <iostream>
#include <memory>
using namespace std;

int main() {
    // before: int* marks = new int[5]; ... delete[] marks;
    unique_ptr<int[]> marks = make_unique<int[]>(5);   // an array version exists too
    for (int i = 0; i < 5; i++) marks[i] = (i + 1) * 10;
    for (int i = 0; i < 5; i++) cout << marks[i] << " ";
    cout << endl;
    return 0;                                           // delete[] happens here, automatically
}

Output:

10 20 30 40 50 

2. A vector of unique_ptrs owns every photo; loop by reference, because a unique_ptr can't be copied. When the vector is destroyed, every photo is freed.

#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;

struct Photo {
    string name;
    Photo(string n) : name(n) { cout << "load " << name << endl; }
    ~Photo() { cout << "free " << name << endl; }
};

int main() {
    vector<unique_ptr<Photo>> gallery;
    gallery.push_back(make_unique<Photo>("beach.jpg"));
    gallery.push_back(make_unique<Photo>("temple.jpg"));
    for (const auto& p : gallery)          // by reference: a unique_ptr can't be copied
        cout << "showing " << p->name << endl;
    cout << "closing gallery" << endl;
    return 0;
}

Output:

load beach.jpg
load temple.jpg
showing beach.jpg
showing temple.jpg
closing gallery
free beach.jpg
free temple.jpg

3.

#include <iostream>
#include <memory>
#include <string>
using namespace std;

int main() {
    auto photo = make_shared<string>("beach.jpg");
    cout << photo.use_count() << endl;
    auto goa = photo;
    auto fav = photo;
    auto best = photo;
    cout << photo.use_count() << endl;
    fav.reset();
    cout << photo.use_count() << endl;
    return 0;
}

Output:

1
4
3

4. If the child also held a shared_ptr to the parent, neither would ever be freed.

#include <iostream>
#include <memory>
#include <string>
using namespace std;

struct Child;
struct Parent {
    string name;
    shared_ptr<Child> child;              // the parent owns the child
    ~Parent() { cout << "free " << name << endl; }
};
struct Child {
    string name;
    weak_ptr<Parent> parent;              // the child only watches the parent
    ~Child() { cout << "free " << name << endl; }
};

int main() {
    auto mom = make_shared<Parent>();
    mom->name = "Sunita";
    mom->child = make_shared<Child>();
    mom->child->name = "Aarav";
    mom->child->parent = mom;
    if (auto p = mom->child->parent.lock())
        cout << mom->child->name << "'s parent: " << p->name << endl;
    cout << "end of main" << endl;
    return 0;
}

Output:

Aarav's parent: Sunita
end of main
free Sunita
free Aarav

Quick quiz

What does this print?

auto a = make_shared<int>(5);
auto b = a;
{
    auto c = a;
    cout << a.use_count();
}
cout << a.use_count();
Answer

32. a and b own the int: 2. Inside the braces c adds a third owner, so it prints 3. At the } c is destroyed: back to 2. There's no space between them, so it prints 32.

Interview questions

  1. What is RAII? Tying a resource's lifetime to an object: acquire it in the constructor, release it in the destructor, which C++ always runs when the object goes out of scope (also during exceptions).
  2. unique_ptr vs shared_ptr? unique_ptr: one owner, not copyable, movable, zero overhead. shared_ptr: shared ownership with a reference count in a control block, copyable, slightly slower.
  3. Why prefer make_unique / make_shared over new? No naked new, exception safety, and make_shared does one allocation for the object and the control block.
  4. How do you transfer ownership of a unique_ptr? std::move: auto b = std::move(a);, after which a is null.
  5. What is a reference cycle and how do you break it? Objects that own each other through shared_ptr never reach a count of 0; make one direction a weak_ptr.
  6. What does weak_ptr::lock() return? A shared_ptr to the object if it's still alive, otherwise an empty one; expired() checks without locking.
  7. Is shared_ptr thread-safe? The reference count is updated atomically; the object it points to is not automatically protected.
  8. When is a raw pointer still fine? For a non-owning view of an object someone else owns (e.g. a function parameter), never for ownership.
  9. What happens if you create two shared_ptrs from the same raw pointer? Two control blocks, two counts, and a double delete.

Glossary

Term Meaning, with an example
heap Memory you rent with new and must give back (episode 10).
memory leak Heap memory that is never given back, e.g. an early return skipped delete.
double delete Deleting the same memory twice: undefined behaviour, often a crash.
dangling pointer A pointer to memory that was already freed.
ownership Being responsible for giving memory back. A raw pointer doesn't say who owns.
scope The { } block a variable lives in; it's destroyed at the closing }.
destructor ~Photo(), run automatically when an object is destroyed (episode 13).
RAII Resource Acquisition Is Initialization: cleanup lives in a destructor, so leaving a scope (by any path) releases the resource.
smart pointer An object that owns heap memory and deletes it in its destructor (<memory>).
unique_ptr A smart pointer with exactly one owner: unique_ptr<Photo> p = make_unique<Photo>("beach.jpg");
make_unique Creates an object on the heap and returns a unique_ptr to it.
deleted function A function switched off with = delete, like unique_ptr's copy constructor.
move() Hands ownership over; the old unique_ptr becomes empty (nullptr).
shared_ptr A smart pointer with many owners; the last one deletes the object.
make_shared Creates an object and its control block in one allocation, returns a shared_ptr.
reference count / use_count() How many shared_ptrs currently own the object.
control block The hidden record a shared_ptr keeps with the counts.
reset() Makes a smart pointer let go of its object (and empty).
reference cycle Objects owning each other through shared_ptr, so none is ever freed.
weak_ptr Watches a shared_ptr-owned object without owning it; doesn't change the count.
lock() Turns a weak_ptr into a shared_ptr if the object still exists.
undefined behaviour Code whose result C++ doesn't define: it may work, print garbage, or crash.
segmentation fault A crash when a program touches memory it may not use.

Summary

  • An early return skipped delete: a leak. Deleting twice: a crash. A raw pointer doesn't say who owns the memory.
  • RAII: put the delete in a destructor, so leaving the scope by any path cleans up, like a hotel cleaning your room at check-out.
  • unique_ptr + make_unique: one owner, freed at the closing }, can't be copied, can be handed over with move(). The default choice.
  • shared_ptr + make_shared: counted owners (use_count()), the last one frees the object.
  • shared_ptrs pointing at each other leak (a cycle). weak_ptr watches without owning; lock() to use it.
  • Modern rule: no naked new / delete.

Next episode: move handed a photo over without copying it. What does it really do, and why can it make programs much faster? Move semantics.