Skip to content

How to read the C++ examples

Difficulty: Beginner

Key concepts

  • C++20
  • validation labels
  • CMake
  • CTest
  • expected output
  • code conventions
  • flawed examples
  • Which version of C++ the examples use, and how newer features are marked.
  • What each validation label above a code block means.
  • The naming and comment conventions in example code.
  • The C++ idioms that appear in almost every example, explained once.
  • How to download, build, test, and run the examples on your own machine.

Every compiled example uses C++20, the version of the C++ standard published in 2020. It is widely supported by current compilers and includes features this site uses, such as defaulted comparison operators.

Newer standards (C++23 and later) add useful features, but compiler support is still uneven. When a lesson mentions one, it appears in a box like this, and it is never used in compiled examples:

Above every code block is a label that says how that code was checked.

  • Verified: compiled with both GCC and Clang with warnings treated as errors, and its tests and output comparison passed in the recorded run. The label’s detail line names the compiler versions and the date of the run.
  • Compiled: compiles with both compilers, but its output is not tested.
  • Illustrative: a short fragment to explain an idea, not compiled on its own. It may leave out includes or surrounding code.
  • Flawed (intentional): shows a mistake on purpose. It is always followed by a corrected version. Do not copy it.
  • Not validated: no passing run is recorded. Treat such code with care.

Labels are generated from the recorded results of the validation run, not typed by hand. The About page describes the process in detail.

Code on the site is not pasted into the pages. Each block is cut from a real source file in the examples project, between marker comments like these:

IllustrativeA fragment for explanation; not compiled on its own.

// [snippet:reading-list]
class ReadingList { /* ... */ };
// [/snippet:reading-list]

The site build reads the file and extracts the code between the markers, so the page cannot drift away from the code that was compiled. The markers are removed from what you see on the page. The title of a code block names the file it came from.

Here is the smoke example used to check the pipeline. The class comes from reading_list.hpp:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

reading_list.hpp
// A list of book titles to read, in the order they were added.
// Invariant: titles are non-empty and unique. Every function below keeps
// that rule true, so code using a ReadingList never has to check it.
class ReadingList {
public:
// Adds a title to the end of the list. Returns false (and changes
// nothing) if the title is empty or already present, true if added.
// `const std::string&` passes the caller's string by reference, so it
// is not copied on the way in, and `const` promises add will not change
// it. push_back makes the one copy the list keeps. A string literal,
// as in add("Design Patterns"), is first turned into a temporary
// std::string for the reference to refer to.
bool add(const std::string& title);
// True if the title is in the list. The `const` after the brackets
// promises that asking does not change the list.
[[nodiscard]] bool contains(const std::string& title) const;
// How many titles there are. noexcept: it cannot throw.
[[nodiscard]] std::size_t size() const noexcept { return titles_.size(); }
// Read-only access to every title, without copying them. The reference
// is valid as long as the list exists, and shows later changes; a
// reference or iterator to one title may be invalidated by the next add.
[[nodiscard]] const std::vector<std::string>& titles() const noexcept { return titles_; }
private:
// The titles themselves, owned by the list. Private, so the only way
// to add one is through add, which checks the invariant.
std::vector<std::string> titles_;
};

The program in main.cpp uses it:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// std::boolalpha makes std::cout print a bool as true or false instead
// of 1 or 0. Each add returns whether the title was added.
std::cout << std::boolalpha;
std::cout << "add Design Patterns: " << list.add("Design Patterns") << '\n';
// A second add of the same title is refused: titles are unique.
std::cout << "add Design Patterns again: " << list.add("Design Patterns") << '\n';
// An empty title is refused too, so the list still holds one title.
std::cout << "add empty title: " << list.add("") << '\n';
std::cout << "size: " << list.size() << '\n';

When a program’s output matters, the page shows it. It comes from the example’s expected_output.txt file, and the test run compares the program’s real output with that file byte for byte:

Expected output
add Design Patterns: true
add Design Patterns again: false
add empty title: false
size: 1

Knowing the conventions makes the examples quicker to read.

  • Namespaces. Each example’s code sits in a namespace such as lld::orientation or lld::classes, so names from different examples never clash.
  • Names. Types use PascalCase (ReadingList), functions and variables use snake_case (add, copies_available), and private data members end in an underscore (titles_), so you can tell at a glance what is part of an object’s hidden state.
  • A header comment at the top of each example file. It states ownership (who is responsible for destroying what), how long returned references stay valid, and whether the types are safe to use from several threads. Snippets often start below it, so open the file to read it.
  • Rules written as comments. A comment starting // Invariant: states a rule the class keeps true at all times, for example “titles are non-empty and unique”.
  • [[nodiscard]] before a function asks the compiler to warn if a caller ignores the result. It is mainly used on queries, functions whose only purpose is to return something.
  • noexcept after a function promises it will not throw an exception.
  • Includes are complete. Each file includes the standard headers it uses; nothing relies on another header including them by accident.
  • Comments explain the why, and the hard lines. A comment above a class or function says what it is for and the idea behind it. A comment beside a line explains anything a newcomer would stop at. Short getters with an obvious name are left without one.
  • “How this code works” boxes. After a dense function, the page explains it step by step, often with a worked example. The box starts open; select its title to fold it away.

The examples use modern C++ (C++20). The same few pieces of syntax appear on nearly every page. Each is explained once here, with what it means and why the examples use it. Code comments mention an idiom where a page first uses it, and this section gives the fuller explanation.

IllustrativeA fragment for explanation; not compiled on its own.

bool add(const std::string& title); // title: the caller's string, read only

std::string& is a reference: another name for the caller’s own string, so nothing is copied. const in front means the function promises not to change it. Together, const T& means “let me read your value without copying it”. The examples use it for anything bigger than a number: strings, vectors, objects. Small values such as int, bool, or a Money holding one integer are passed by value instead, because copying them costs nothing.

IllustrativeA fragment for explanation; not compiled on its own.

[[nodiscard]] std::size_t size() const noexcept { return titles_.size(); }

A const after the brackets promises that calling the function does not change the object. The compiler holds the function to it: inside, the object’s members cannot be modified. Queries (functions that only answer a question) are const; only a const function can be called through a const reference, so this is also what lets a caller read an object it was given read-only.

[[nodiscard]] asks the compiler to warn when a caller ignores the result, because ignoring it is almost always a bug: calling contains and not looking at the answer does nothing. The examples build with warnings treated as errors, so it really is checked.

When a test or a demo ignores a result on purpose, it writes static_cast<void>(game.play(...)). Converting the result to void says “thrown away deliberately”, and silences the warning for that one call only.

noexcept after a function promises it never throws an exception. It documents the promise and lets the compiler and the standard library rely on it; for example, when a std::vector grows, it prefers to move its elements if their move constructor is noexcept, and otherwise copies them when it can. If a noexcept function does throw, the program stops at once (std::terminate), so the examples use it only where it is plainly true.

IllustrativeA fragment for explanation; not compiled on its own.

explicit Id(std::string value);

Without explicit, C++ will silently turn a std::string into an Id wherever an Id is expected. explicit forbids that, so you have to write Id("tea-500g") and mean it. The examples mark one-argument constructors explicit unless the conversion is genuinely harmless.

IllustrativeA fragment for explanation; not compiled on its own.

enum class Mark { x, o };
Mark m = Mark::x; // the name is inside the type: Mark::x, not x

An enum class is a type with a fixed list of named values. Unlike an older plain enum, its names do not leak into the surrounding code, and it does not convert to an int by itself, so a Mark cannot be compared with a number by mistake. The examples use one wherever a value is “one of these few things”: a game state, a result, a status.

auto lets the compiler work out a variable’s type from the value it is given: const auto found = map.find(key); saves writing std::map<Sku, Product>::const_iterator (the type when map is const). const auto& is “a read-only reference, of whatever type this is”, used in loops so that elements are not copied. The examples use auto where the type is obvious or long, and write the type out where it tells the reader something.

IllustrativeA fragment for explanation; not compiled on its own.

for (const std::string& title : titles_) { /* each title in turn */ }
for (const auto& [sku, quantity] : stock) { /* each entry of a map */ }

A range-for visits every element of a container in order. A structured binding, the [sku, quantity] part, unpacks something with several parts (a pair, a map entry, a small struct) into separate names. In a std::map, each entry is a pair of key and value, so [sku, quantity] names both.

IllustrativeA fragment for explanation; not compiled on its own.

const auto is = [&](int row, int col) { return mark_at(row, col) == mark; };

A lambda is a small function written where it is needed. Read it in three parts:

  • [&] is the capture: which outside variables the lambda may use. [&] means “use any of them, by reference”, [this] means “use this object’s members”, and [] means “none”. [&x, y] names them: x by reference and a copy of y. Inside a member function, [&] also lets the lambda use the object’s members, which is how is can call mark_at. The examples keep a lambda that captures by reference inside the function that made it, so the captured variables are still alive whenever it runs;
  • (int row, int col) are its parameters, as in any function;
  • { ... } is its body.

The result is stored in a variable (is) and called like a function: is(1, 1). Lambdas also appear as arguments, as in std::all_of(begin, end, [](const auto& cell) { return cell.has_value(); }), which asks the lambda about every cell.

std::optional: a value that may be missing

Section titled “std::optional: a value that may be missing”

IllustrativeA fragment for explanation; not compiled on its own.

std::optional<Mark> mark_at(int row, int col) const; // a Mark, or nothing
if (const auto mark = board.mark_at(1, 1)) { use(*mark); }

std::optional<T> either holds a T or holds nothing (std::nullopt). It puts “there may be no answer” into the type, instead of a special value such as -1 or an empty string that a caller might forget to check. An optional converts to true when it holds a value; *mark or mark.value() reads the value, and mark.has_value() asks whether there is one. Reading an empty optional with * is undefined behaviour, so the examples always check first.

Smart pointers: std::unique_ptr and std::make_unique

Section titled “Smart pointers: std::unique_ptr and std::make_unique”

IllustrativeA fragment for explanation; not compiled on its own.

std::vector<std::unique_ptr<Promotion>> promotions;
promotions.push_back(std::make_unique<MultiBuy>("3 for 2", tea, 3, 2));

A std::unique_ptr<T> owns one object on the heap and deletes it automatically when the pointer itself is destroyed, so nothing leaks and nothing is deleted twice. There is exactly one owner at a time: a unique_ptr cannot be copied, only moved. std::make_unique<T>(arguments) creates the object and the pointer in one step. The examples use it to own an object through its interface, as above, where the vector holds different kinds of promotion. A plain T* or T& in the examples never owns anything; it only refers to an object someone else owns. std::shared_ptr, with several owners, appears only where sharing is really needed, and the page says why.

std::move(x) does not move anything by itself. It marks x as “I am finished with this value”, which allows the next operation to take its contents instead of copying them. titles_.push_back(std::move(title)) hands the string over cheaply. That only works if title is not const, for example a parameter taken by value: moving from a const object silently copies it. After a move, x is still a valid object, but its value is not specified, so the examples do not read it again until they assign a new value.

std::variant, std::get_if, and std::holds_alternative

Section titled “std::variant, std::get_if, and std::holds_alternative”

IllustrativeA fragment for explanation; not compiled on its own.

using State = std::variant<Idle, AwaitingPin, Ready>; // exactly one of these
if (const auto* ready = std::get_if<Ready>(&state_)) { use(ready->session); }

A std::variant holds exactly one value out of a fixed list of types, and knows which one. The examples use it for states: each state is a small struct holding only the data that exists in that state. std::get_if<Ready>(&state_) returns a pointer to the Ready value if that is what the variant holds, or nullptr if it holds something else, so the if runs only in that state. std::holds_alternative<Ready>(state_) asks the same question and returns a bool. std::visit calls a function with whichever value is held.

IllustrativeA fragment for explanation; not compiled on its own.

class Promotion {
public:
virtual ~Promotion() = default;
[[nodiscard]] virtual Money discount(const Cart& cart) const = 0;
};
class MultiBuy final : public Promotion {
public:
[[nodiscard]] Money discount(const Cart& cart) const override;
};

An interface in C++ is a class whose functions, apart from the destructor, are virtual ... = 0: they have no body here, and any class you want to create objects of must provide one. Calling discount through a Promotion& runs the derived class’s version. override asks the compiler to check that the function really replaces one in the base class, which catches a misspelled name or a missing const. final says no class may derive from this one. The virtual destructor makes deleting an object through a base-class pointer, as a unique_ptr<Promotion> does, run the right destructor.

Many interfaces in the examples make their copy operations protected, or delete them. Then code holding two Promotion& cannot write a = b;, which would copy only the base part of one object into the other (called slicing), while the derived classes can still be copied if they choose.

= default asks the compiler to write the usual version of a special function, such as a destructor, copy, or comparison. = delete forbids a function, so that calling it fails to compile. Deleting both Thing(const Thing&) (copy construction) and Thing& operator=(const Thing&) (copy assignment) makes a type impossible to copy; deleting only the first still lets a = b; compile.

friend auto operator<=>(const Money&, const Money&) = default; gives a type all six comparisons (<, <=, >, >=, ==, !=) at once, comparing the members in order. The examples use it for small value types such as money and ids, which need sorting and comparison but nothing unusual.

constexpr means “can be worked out while compiling”. On a variable, static constexpr int size = 3; is a constant shared by every object of the class, fixed at compile time. On a function, it allows the function to be evaluated at compile time when its arguments are known, and otherwise it runs like any other function.

IllustrativeA fragment for explanation; not compiled on its own.

if (const auto found = map.find(key); found != map.end()) { use(found->second); }

An if may start with a declaration, then a ;, then the condition. The variable exists only inside the if and its else, which keeps short-lived names out of the rest of the function.

A std::string_view is a read-only window onto characters stored somewhere else: a string literal, or part of a std::string. It is cheap to pass, and the examples use it for parameters that only read text. Because it does not own the characters, a string_view must not outlive the string it looks at, so the examples never store one that points into a temporary string.

The examples use exceptions for programming errors and broken contracts: std::invalid_argument for a bad argument, std::logic_error for a call that should never happen, std::out_of_range for an index off the end. Results a caller should expect, such as “the cell is taken” or “the card was declined”, are returned as values, usually an enum class, never thrown. The lesson on errors and contracts in the C++ section explains the choice.

Some lessons show a mistake before fixing it, because seeing why a design fails is often the fastest way to understand the better one. Flawed code:

  • is labeled Flawed (intentional), and starts with a comment saying what is wrong;
  • lives in a separate flawed/ directory of the examples project;
  • is compiled, if it can be compiled safely, but never run as a test;
  • is always followed on the page by the corrected version.

If a flawed example would crash or behave unpredictably when run, it is only compiled, never executed.

One kind of flawed code is an exception to the second and third rules: the start code of the refactoring exercises. It is labeled Flawed (intentional) because its structure is what the exercise fixes, so it is not code to copy. It lives in a start/ directory, and it is run, because its characterization tests pin what it does today. Its corrected version is the reference solution that follows it on the page.

Building and running the examples yourself

Section titled “Building and running the examples yourself”

Every compiled example on the site is in one download, with its build files and tests: lld-examples.tar. It needs:

  • CMake 3.21 or later (the build tool that generates the build and runs the tests through its companion tool, CTest);
  • make, because the presets use CMake’s “Unix Makefiles” generator (the archive’s README.md shows how to use another, such as Ninja, without presets);
  • a C++20 compiler. The recorded runs use GCC 11.4 and Clang 14; other recent versions should work but are not checked.

Extract the archive and build everything with a CMake preset (a named set of build settings stored in CMakePresets.json):

IllustrativeA fragment for explanation; not compiled on its own.

Terminal window
tar -xf lld-examples.tar
cd lld-examples
cmake --preset gcc-debug # configure: choose compiler and settings
cmake --build --preset gcc-debug # compile every example and test
ctest --preset gcc-debug # run all tests and output comparisons

Use clang-debug instead of gcc-debug to build with Clang. To run one example program, call it from the build directory; the path follows the example’s directory:

IllustrativeA fragment for explanation; not compiled on its own.

Terminal window
./build/gcc-debug/orientation/hello-design/hello_design

If your CMake is older or presets are unavailable, the archive’s README.md lists the equivalent commands without presets.

Each example directory follows the same layout: header and source files for the design, main.cpp for a runnable scenario, test_*.cpp for tests, and expected_output.txt for the program’s verified output. The build basics and testing basics lessons in the C++ section explain CMake and the test harness in more depth.

Exercise: Build an example and compare its output

Download and extract the examples, then:

  1. Build them with either preset and run all tests with ctest.
  2. Run the hello_design program and compare its output with the expected output shown above.
  3. Open orientation/hello-design/main.cpp. In the line labeled add Design Patterns again, change the argument "Design Patterns" to "Refactoring". Rebuild with cmake --build --preset gcc-debug (running ctest alone does not rebuild), then run ctest again. What happens, and why?
Show the explained answer
  1. All tests should pass. The summary line reads 100% tests passed, 0 tests failed, followed by the number of tests.
  2. The output should match the expected output exactly, line by line.
  3. The program now adds a new title instead of a duplicate, so it prints add Design Patterns again: true (the label text did not change, only the argument) and size: 2. The output no longer matches expected_output.txt, so the test named hello_design.output fails. That is the comparison doing its job: the recorded output is a promise about the program’s behaviour, and any change in behaviour is caught. To accept a deliberate change, you would update expected_output.txt, and a reviewer would see that change.

If step 1 fails to configure, check your CMake version (cmake --version) and that a C++20 compiler is installed. If the preset is not found, use the commands without presets from the archive’s README.md.

  • Compiled examples use C++20; later-standard features appear only in labeled notes.
  • The label above each code block says how it was checked: Verified, Compiled, Illustrative, Flawed (intentional), or Not validated.
  • Code is extracted from real source files, so pages match what was compiled.
  • Flawed examples are labeled, isolated, never run as tests, and always followed by a fix; the start code of the refactoring exercises is the one exception that is run.
  • Download the examples and build them with cmake --preset, then run ctest.