Smart Pointers
What smart pointers solve
The three smart pointer types
Type | Ownership | Copyable? | Typical use |
|---|---|---|---|
unique_ptr<T> | Exclusive — only one owner at a time | No (move-only) | Default choice for owning a heap object |
shared_ptr<T> | Shared — reference-counted, multiple owners | Yes | When multiple parts of the code must jointly own an object |
weak_ptr<T> | None — a non-owning observer of a shared_ptr | Yes | Breaking reference cycles, observing without extending lifetime |
The general principle: stop calling new/delete directly
Preferred creation: make_unique and make_shared
make_unique_shared.cpp
#include <memory>
#include <iostream>
struct Point {
int x, y;
Point(int x, int y) : x(x), y(y) {}
};
int main() {
auto up = std::make_unique<Point>(3, 4); // preferred
auto sp = std::make_shared<Point>(5, 6); // preferred
std::cout << up->x << ", " << up->y << std::endl;
std::cout << sp->x << ", " << sp->y << std::endl;
// No delete needed anywhere — both are freed automatically
// when up and sp go out of scope.
return 0;
}unique_ptr: exclusive ownership, cannot be copied, extremely low overhead — the default choice.
shared_ptr: shared ownership via reference counting — use when genuinely multiple owners are needed.
weak_ptr: a non-owning reference to a shared_ptr's object — used to avoid reference cycles.
Always prefer std::make_unique / std::make_shared over calling new directly.