RAII and smart pointers in C++: ownership without leaks
What RAII means, why modern C++ code rarely calls delete, and how to use std::unique_ptr, std::shared_ptr and the rule of zero, with examples from real projects.
RAII (Resource Acquisition Is Initialisation) is the most important idea in C++: tie every resource to an object whose destructor releases it. Memory, files, locks and sockets are then released automatically, even when an exception is thrown.
The idea in one example
{
std::ofstream log("store.log", std::ios::app); // opens the file
std::lock_guard lock(mutex); // locks the mutex
log << record;
} // leaving the scope: unlocks the mutex, closes the file, in that orderNo close(), no unlock(), and nothing leaks if << throws.
std::unique_ptr: one owner
struct Node {
std::array<std::unique_ptr<Node>, 26> children;
std::optional<std::int64_t> weight;
};
child = std::make_unique<Node>(); // allocate
child.reset(); // delete the child and its whole subtreeA trie built like this (as in search suggestions for Findly) frees everything when the root goes away. There's no destructor to write.
std::shared_ptr: shared ownership
Use it when no single owner outlives the rest. A thread pool, for example, wraps a move-only
std::packaged_task so a copyable callback can own it:
auto task = std::make_shared<std::packaged_task<int()>>(std::move(work));
queue.push([task] { (*task)(); });See a thread pool for Batchworks.
The rule of zero
If every member manages itself (std::string, std::vector, std::unique_ptr), your class needs
no destructor, copy or move operations: the compiler-generated ones are correct. Write them only
for classes that directly own a raw resource, and then usually delete the copy operations:
class Pool {
public:
~Pool(); // releases the buffer
Pool(const Pool&) = delete; // two pools must never own one buffer
Pool& operator=(const Pool&) = delete;
};Raw memory, done carefully
Allocators separate allocating memory from constructing objects in it, using placement new and explicit destruction:
T* object = ::new (block) T(std::forward<Args>(args)...); // construct in existing memory
std::destroy_at(object); // destroy without freeingIt's the one place raw memory belongs, wrapped in a class with clear ownership. Build one in memory pools for Pixelforge.
Questions and answers
- Should I ever use new and delete in modern C++?
- Almost never directly. Use std::make_unique (or containers) to allocate and let destructors release. Raw new/delete belong inside low-level building blocks like allocators, wrapped in a class that owns the memory.
- unique_ptr or shared_ptr?
- unique_ptr by default: one clear owner, no overhead. Use shared_ptr only when ownership is genuinely shared and no single object outlives the others, for example a task captured by a callback in another thread.
Practise it in a project
These projects put this guide to work, with tickets, tests and code review.
Pixelforge
Memory pools for Pixelforge
Stop frame stutters in Pixelforge's engine with a fixed-size block allocator: an intrusive free list, alignment, misuse detection, then a typed object pool with RAII handles.
- manual memory management
- alignment
- placement new
- RAII and templates
Findly
Search suggestions for Findly
Build the autocomplete behind Findly's search box with a trie, then add 'did you mean' suggestions using edit distance computed along the trie.
- tries
- tree ownership
- edit distance
- dynamic programming
Batchworks
A thread pool for Batchworks
Replace thread-per-job with a fixed pool of workers: a shared task queue, graceful shutdown, failure accounting, futures for results and a parallel_for.
- threads
- task queues
- futures
- shutdown semantics