Chapter 19: C++
C++ keeps C’s control over memory and layout and adds the tools to make that control safe: destructors that release resources automatically, move semantics that transfer ownership without copying, templates that generate code per type at no run-time cost, and, since C++20, concepts and coroutines. The price is that the language exposes every one of those mechanisms. To use std::vector well you need to know that allocation is not construction; to use std::function well you need to know what type erasure costs. This chapter builds the library pieces themselves so that those costs become visible.
Concepts from other sections (15)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Coroutine: a function that can suspend and later resume, keeping its locals in a heap-allocated frame. Read more: 19.6 Coroutine generator
- Type erasure: hiding a concrete type behind a uniform interface so unrelated types can be stored as one type. Read more: 19.7 Function: type erasure with a small buffer
- Expression template: a type that represents an unevaluated expression, evaluated later in one pass. Read more: 19.5 Expression templates
- Rule of five: a type that manages a resource defines (or deletes) the copy and move constructors, copy and move assignment, and destructor together. Read more: 19.1 Vector
- RAII: Resource Acquisition Is Initialization; tying a resource’s release to an object’s destructor. Read more: 19.2 UniquePtr
- Move-only type: a type that can be moved but not copied, so ownership can transfer but never duplicate. Read more: 19.2 UniquePtr
- Raw storage: allocated memory in which no object has yet been constructed. Read more: 19.1 Vector
- Copy-and-swap: implementing assignment by copying into a temporary and swapping, so failure cannot damage the target. Read more: 19.1 Vector
- Blocking queue: a queue whose operations wait, rather than fail, when it is full or empty. Read more: 19.4 Thread-safe queue
- Condition variable: a primitive that lets a thread sleep until another thread signals that shared state may have changed. Read more: 18.7 Thread pool
- CRTP: the curiously recurring template pattern,
class D : Base<D>, letting the base call the derived type statically. Read more: 19.5 Expression templates - Vtable: a table of function pointers used for dynamic dispatch, here written by hand. Read more: 19.7 Function: type erasure with a small buffer
- Breadth-first search (BFS): traversal in order of hop distance using a FIFO queue. Read more: 18.6 Graph as an adjacency list
- Depth-first search (DFS): traversal that follows one path as far as possible before backtracking, using a stack. Read more: 18.6 Graph as an adjacency list
- Intrusive free list: a list of free blocks whose links are stored inside the free blocks themselves. Read more: 19.9 Memory pool allocator
Each of the nine exercises has a reference implementation in a single header and a walkthrough. The arc starts with ownership and object lifetime (a vector and a unique pointer), moves to compile-time programming (a constexpr matrix and expression templates), then to concurrency and coroutines (a thread-safe queue and a generator), and finishes with type erasure, concepts, and a custom allocator. Each section states the problem and its constraints, builds the design from first principles, walks through annotated code, explains why the design beats the alternatives, and closes with review questions.
Learning objectives
- Manage object lifetime explicitly: separate allocation from construction, and implement the rule of five with correct exception guarantees.
- Use RAII and move-only types to make ownership a compile-time property.
- Move work and checks to compile time with templates,
constexpr,requires, and concepts.- Build concurrent and lazy abstractions with
std::condition_variableand C++20 coroutines.- Implement type erasure and a standard-library-compatible allocator, and explain their costs.
Before you begin
Section titled “Before you begin”You should be comfortable with C++ classes, references, and basic templates, and with the C memory model. The C chapter is the natural predecessor: several sections here (the vector, the queue, the allocator) are the C++ counterparts of C exercises and refer back to them.
The language in brief
Section titled “The language in brief”Memory in C++ is managed through RAII: a resource is acquired in a constructor and released in a destructor, so cleanup happens on every exit path, including exceptions. Smart pointers (unique_ptr for one owner, shared_ptr for shared ownership) apply that to heap memory, and stack allocation is preferred where it fits.
The type system is strongly and statically typed. Templates generate code per type, C++20 concepts constrain them, and auto deduces types where spelling them adds nothing. Errors are reported with exceptions (to be used judiciously), std::optional for absence, and, from C++23, std::expected for a value or an error. Concurrency comes from std::thread, std::async, and std::atomic, and C++20 adds coroutines. Builds use cmake with g++ or clang++; C++20 also has modules, and many libraries are header-only. The exercises use C++20, which is preferred here; C++23 also works.
Idioms to practise
Section titled “Idioms to practise”- RAII everywhere: destructors do the cleanup, and there is no manual
delete. - Move semantics:
std::move, rvalue references, and the rule of five (or zero). - SFINAE and concepts to constrain templates at compile time.
- Range-based
forwith structured bindings. std::variantwithstd::visitfor sum types.- CRTP (the curiously recurring template pattern) for static polymorphism.
constexprfor compile-time computation.
Building and running the exercises
Section titled “Building and running the exercises”Each exercise directory holds a header with the reference implementation, a main.cpp test suite, and the walkthrough. Every exercise is a single translation unit. To build and run one:
cd practice/build/systems/cpp/01-vectorc++ -std=c++20 -Wall -Wextra -O2 main.cpp -o vector && ./vectorThe test program prints ok ... and exits 0 when every check holds. The thread-safe queue needs -pthread and ships a run.sh that adds it.
In this chapter
Section titled “In this chapter”The exercises are ordered by concept, not by difficulty, so if you are choosing where to start, the difficulty rating (1 is easiest, 5 hardest) is a better guide than the number. There is no exercise 03.
- Vector (difficulty 3). A
std::vectorwork-alike that separates raw storage from live objects, grows withmove_if_noexcept, and implements the rule of five with copy-and-swap. - UniquePtr (difficulty 2). A move-only owning pointer with custom deleters and an array specialisation, and the exact order of operations that makes
resetand self-move safe. - Compile-time matrix (difficulty 3). A matrix whose dimensions live in its type, so shape errors fail to compile, with
requires-constrained square-only members andconstexprarithmetic. - Thread-safe queue (difficulty 3). A bounded blocking queue built from one mutex and two condition variables, with a
closethat wakes everyone and still delivers the backlog. - Expression templates (difficulty 4). Lazy vector arithmetic with CRTP that computes
a + b + cin one pass, and the storage rule that keepsautoexpressions from dangling. - Coroutine generator (difficulty 4). A
Generator<T>over the C++20 coroutine protocol: lazy start, owned frames, exceptions delivered to the consumer. - Function: type erasure with a small buffer (difficulty 4). A
std::functionclone with a hand-written vtable that stores small callables inline and supports move-only captures. - Graph with concepts (difficulty 3). BFS, DFS, shortest path, and Dijkstra written once against a concept and run on three unrelated graph types.
- Memory pool allocator (difficulty 4). A fixed-size block allocator with an intrusive free list, and the standard-library adaptor that lets
std::listandstd::mapuse it.
Exercise 03 was a hash map. Six hash maps across the exercises were consolidated into two worked sections of Algorithms: A Swiss table, in C, and A Robin Hood hash map, in Rust, both in the Systems data structures chapter.
Key terms
Section titled “Key terms”- Move semantics: transferring the resources of an object that is about to be discarded (an rvalue) to a new owner by taking its pointers instead of copying what they point at;
std::movecasts a value to an rvalue to request it. - Smart pointer: a class that owns a heap object and frees it in its destructor, applying RAII to memory;
std::unique_ptrhas exactly one owner andstd::shared_ptrcounts shared owners.
Further reading
Section titled “Further reading”- cppreference.com: the authoritative reference.
- ISO C++ FAQ: answers to common questions.
- A Tour of C++ by Bjarne Stroustrup, 3rd edition: a concise modern overview.
- Effective Modern C++ by Scott Meyers: the essential C++11/14 patterns.
- C++ Core Guidelines: free, maintained by Stroustrup and Sutter.