[Intermediate] — RAII for memory, off the shelf. The reason modern C++ contains almost no new and no delete at all.
Why
Widget *w = new Widget();
do_something(); // if this throws, w LEAKS
delete w;Manual new/delete has every failure mode from C’s memory management, plus exceptions creating new paths out of a function that skip your delete.
Smart pointers apply RAII: the pointer is an object, and its destructor frees.
Modern C++ rule: no raw
new, no rawdelete, ever. If you typedelete, you’re writing 2005 C++ or implementing a container.
std::unique_ptr — the default
#include <memory>
auto w = std::make_unique<Widget>(arg1, arg2); // ALWAYS prefer make_unique
std::unique_ptr<Widget> w(new Widget()); // works; don't
w->method();
(*w).method();
Widget *raw = w.get(); // borrow, without transferring ownership
w.reset(); // delete now
w.reset(new Widget()); // delete and take a new one
Widget *r = w.release(); // give up ownership — YOU must delete it now
if (w) { } // null checkExactly one owner. unique_ptr is move-only — it cannot be copied:
auto a = std::make_unique<Widget>();
auto b = a; // ERROR — copy is deleted
auto b = std::move(a); // ownership transfers; a is now nullThis is Rust’s ownership as a library type. The difference is that Rust makes using the moved-from a a compile error; C++ leaves you a null pointer to dereference.
Zero overhead. A unique_ptr is the size of a raw pointer, and its operations inline away. There is no reason to use a raw owning pointer instead.
auto arr = std::make_unique<int[]>(100); // array form — calls delete[]
arr[0] = 1;Custom deleters
auto closer = [](FILE *f) { if (f) std::fclose(f); };
std::unique_ptr<FILE, decltype(closer)> file(std::fopen("x.txt", "r"), closer);This is how you wrap any C API’s create/destroy pair without writing a class — and it’s the answer to “should I write my own RAII wrapper?” most of the time. → C’s stdlib is full of these pairs.
std::shared_ptr — when ownership is genuinely shared
auto a = std::make_shared<Widget>();
auto b = a; // both own it; refcount == 2
std::cout << a.use_count(); // 2Reference counted. The object is destroyed when the last shared_ptr goes away.
It is not free:
- Two allocations with
new(control block + object); one withmake_shared, which is why you use it - Twice the size of a raw pointer (object pointer + control block pointer)
- Atomic refcount updates on every copy and destruction — a real cost in hot paths and across threads
- Thread-safe count, NOT thread-safe object. Two threads sharing a
shared_ptr<Widget>still need a mutex around theWidgetitself.
Use
unique_ptrby default. Reach forshared_ptronly when ownership is genuinely shared and no single owner outlives the others.shared_ptreverywhere is a common code smell — usually it means nobody worked out who owns what.
std::weak_ptr — breaking cycles
struct Node {
std::shared_ptr<Node> next;
std::weak_ptr<Node> parent; // does NOT keep the parent alive
};
if (auto p = node->parent.lock()) { // returns shared_ptr, or null if it's gone
p->do_something();
}Two shared_ptrs pointing at each other never reach zero and never free. Reference counting cannot collect cycles — this is a real leak, not a theoretical one, and it’s the classic parent/child tree bug.
The convention, identical to Rust’s `Rc`/`Weak`: owners hold shared_ptr downward, back-references are weak_ptr.
weak_ptr can’t be dereferenced directly — you must lock() it, which is what makes checking for expiry unavoidable.
Expressing ownership in signatures
This is where smart pointers pay off most: the parameter type documents the ownership contract, and the compiler enforces it.
void observe(const Widget &w); // I look at it. I don't own it. It must exist.
void observe(const Widget *w); // same, but may be null.
void consume(std::unique_ptr<Widget> w); // I TAKE ownership. Caller must std::move.
void share(std::shared_ptr<Widget> w); // I take part-ownership and may outlive you.
std::unique_ptr<Widget> create(); // I give you ownership.
Widget &get_ref(); // I keep ownership; here's a view.Take
const T&orT*unless you’re taking ownership. Passingconst std::shared_ptr<T>&to a function that just reads the object is a common mistake — it couples the callee to the ownership model for no reason. Takeconst T&.
That guidance turns a whole category of “who frees this?” questions into something readable from the signature — which is the same thing a doc comment does in C, except the compiler checks it.
When a raw pointer is still correct
Raw pointers are fine, and idiomatic, for non-owning observation:
class Widget {
Parent *parent_; // non-owning back-reference; parent outlives us
public:
void set_parent(Parent *p) { parent_ = p; }
};The rule: a raw pointer never owns. It’s a nullable view. If it might be null, use T*; if it can’t, use T&.
new and delete, for completeness
Widget *w = new Widget(); // allocate + construct
delete w; // destruct + deallocate
int *arr = new int[100];
delete[] arr; // MUST match — delete on new[] is UBYou need to recognise these in older code. Two classic bugs:
Mismatched forms — delete on a new[] allocation is UB.
Deleting a derived object through a base pointer without a virtual destructor:
Base *p = new Derived();
delete p; // UB unless ~Base() is virtual → leaks the Derived part→ Inheritance and Virtual Dispatch
std::optional — absence without a pointer
#include <optional>
std::optional<Widget> find(int id) {
if (!exists(id)) return std::nullopt;
return Widget(id);
}
if (auto w = find(42)) {
w->use();
}
int v = opt.value_or(0);Since C++17, this is the right way to express “might not be there” for a value — no pointer, no allocation, no null. It’s Option<T> from Rust, with one important difference: *opt on an empty optional is undefined behaviour, not a compile error. .value() throws instead; operator* doesn’t check.
Related C++17 vocabulary types:
std::variant<int, std::string> // a type-safe union → tagged union, checked
std::any // holds anything; requires any_cast
std::span<T> // C++20: a non-owning pointer + length view
std::string_view // a non-owning view into a stringstd::span and std::string_view are the fix for C’s array decay — a pointer that carries its length:
void process(std::span<const int> data) { // accepts vector, array, C array
for (int x : data) { } // knows its size
}Views don’t own. A string_view into a temporary dangles exactly like a reference does:
std::string_view sv = std::string("temp"); // DANGLING immediatelyPractical rules
make_uniqueby default. No rawnew.shared_ptronly for genuinely shared ownership, and prefermake_shared.weak_ptrfor back-references, to break cycles.- Raw pointers and references never own — they observe.
- Take
const T&unless you’re taking ownership. std::optionalfor maybe-a-value, not a pointer.std::span/std::string_viewfor non-owning views, and watch their lifetimes.
Related
- Classes and RAII — the mechanism these are built on
- Copy, Move and the Rule of Five — why
unique_ptris move-only - Rust: Smart Pointers —
Box/Rc/Weak, the same set - C: Memory Management — what this replaces
- C++ course map
Software engineering
Infrastructure & security
Computer science
Hardware & engineering