Smart pointers and ownership
Course contents (20 lessons)
- Getting started
- Setting up a C++ compiler and writing your first program
- Variables, types and reading input
- Control flow, functions and indirection
- Control flow: if, switch and loops
- Functions: parameters, return values and overloading
- References and pointers
- Working with data
- Arrays and std::vector
- Working with std::string and string_view
- Classes and object-oriented design
- Structs and classes: your own types
- Constructors, destructors and RAII
- Operator overloading
- Inheritance and virtual functions
- Generic code and the STL
- Templates: writing generic code
- The STL: containers and iterators
- Algorithms and lambdas
- Ownership, moves and errors
- Smart pointers and ownership
- Move semantics and perfect forwarding basics
- Error handling: exceptions, optional and expected
- Modern C++ and a real project
- Modern C++: ranges, concepts and std::format
- Building projects with CMake
- Final project: a command-line expense tracker
Who owns this object?
Every object in a C++ program needs one answer to the question "who is responsible for destroying you?". Local variables answer it themselves: the scope that declares them. Objects created on the heap have no automatic owner, and that is the source of leaks, double deletes and use-after-free bugs.
The old way was new and delete:
Widget* w = new Widget{};
use(*w);
delete w; // forget this, or return early, or throw above, and it leaks
The modern way is to give the heap object an owner that cleans up by itself, following the RAII idea from earlier. That owner is a smart pointer.
std::unique_ptr: one owner
A unique_ptr owns an object exclusively. When the pointer is destroyed, the object is destroyed. It cannot be copied, because two owners would be a bug, but it can be moved to transfer ownership. Make one with std::make_unique.
#include <iostream>
#include <memory>
#include <string>
struct Connection {
explicit Connection(std::string host) : host_{std::move(host)} {
std::cout << "open " << host_ << "\n";
}
~Connection() { std::cout << "close " << host_ << "\n"; }
void send(const std::string& msg) const { std::cout << host_ << " <- " << msg << "\n"; }
private:
std::string host_;
};
std::unique_ptr<Connection> connect(const std::string& host) {
auto c = std::make_unique<Connection>(host);
c->send("hello");
return c; // ownership moves out to the caller
}
int main() {
auto conn = connect("db.example.com");
conn->send("query");
// auto copy = conn; // error: unique_ptr cannot be copied
auto other = std::move(conn); // ownership moves; conn is now null
std::cout << std::boolalpha << (conn == nullptr) << "\n"; // true
} // "close db.example.com" printed here
The arrow operator reaches the object's members, and *conn gives the object itself. The compiler enforces the single-owner rule: trying to copy is an error, which turns a whole class of runtime bugs into compile-time ones. unique_ptr has almost no overhead compared with a raw pointer. This is the type you should reach for first.
Passing them around
- A function that only uses the object takes a reference or a raw pointer:
void show(const Connection& c). Call it withshow(*conn). The function does not care how the object is owned. - A function that takes ownership accepts
std::unique_ptr<Connection>by value. The caller must writestd::move(conn), which makes the hand-over visible at the call site. - A function that creates an object for the caller returns a
unique_ptr.
std::shared_ptr: shared ownership
Sometimes several parts of the program really do share an object, and none of them can say who finishes last. A shared_ptr keeps a reference count. Each copy increases it. When the last copy dies, the object is destroyed.
#include <memory>
#include <iostream>
struct Config { int timeout{30}; };
int main() {
auto cfg = std::make_shared<Config>();
std::cout << cfg.use_count() << "\n"; // 1
auto another = cfg; // copy: count is now 2
another->timeout = 60;
std::cout << cfg->timeout << "\n"; // 60: same object
std::cout << cfg.use_count() << "\n"; // 2
}
Shared pointers cost more: the count is stored in a control block and updated atomically, which is slower than a plain pointer. They also make it harder to reason about lifetime, since the object may live as long as any holder does. My rule: start with unique_ptr, and use shared_ptr only when sharing is a real requirement of the design.
std::weak_ptr and cycles
Shared pointers have one well-known weakness. If object A holds a shared_ptr to B and B holds a shared_ptr back to A, neither count ever reaches zero, and both leak. A weak_ptr observes a shared object without keeping it alive. You turn it into a shared_ptr with lock() when you need to use it. If the object has gone, lock() returns an empty pointer.
struct Parent;
struct Child {
std::weak_ptr<Parent> parent; // back link does not own
};
struct Parent {
std::shared_ptr<Child> child; // forward link owns
};
int main() {
auto p = std::make_shared<Parent>();
p->child = std::make_shared<Child>();
p->child->parent = p;
if (auto strong = p->child->parent.lock()) {
std::cout << "parent is alive\n";
}
} // both destroyed correctly
A good picture: ownership arrows point down a tree, and non-owning links point up or sideways with raw pointers, references or weak_ptr.
make_unique and make_shared
Prefer the make functions to writing new yourself. They are shorter, they avoid a rare leak when a call has several arguments that can throw, and make_shared allocates the object and its control block in one go.
Polymorphism and custom cleanup
A unique_ptr<Base> may hold a derived object, as in the shapes example. The base class needs a virtual destructor. You can also give a smart pointer a custom deleter for things that are not freed with delete, for example a C library handle:
#include <cstdio>
#include <memory>
using FilePtr = std::unique_ptr<std::FILE, decltype(&std::fclose)>;
FilePtr open(const char* path) {
return FilePtr{std::fopen(path, "r"), &std::fclose};
}
The common mistake
Creating two separate shared_ptrs from the same raw pointer. Each makes its own count and each will delete the object, giving a double free. Create a shared_ptr once, with make_shared, and copy that. A second mistake is using shared_ptr everywhere "to be safe". It hides unclear design, and cycles then leak memory quietly. And calling .get() to hand a raw pointer to something that stores it beyond the owner's lifetime.
Try it yourself
- Rewrite the
Shapeexample so a factory functionmakeShape(std::string kind)returnsstd::unique_ptr<Shape>. - Build a linked list with
unique_ptrfor the next node. What happens to the destructor when the list is very long? (Think about recursion depth.) - Create the parent and child example with two
shared_ptrlinks instead of aweak_ptr. Add destructor messages and confirm the leak.
Widget* w = new Widget{};
use(*w);
delete w; // forget this, or return early, or throw above, and it leaks
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account