Skip to contents
OpenLearningTHE STUDY LIBRARY

In depth study guide · Edition 2026.12

Modern C++: values, ownership, and reliable programs

A practical C++17 study book with diagrams, worked programs, and a complete study-log project

Learn to reason about C++17 programs from types and functions through resource lifetime, containers, algorithms, testing, and an integrated capstone.

14 chapters9 diagrams28 practice tasks

Before you begin

How to use this guide

Beginners who have written a few small programs, and developers revisiting C++ with an ownership-first approach.

Helpful background

What you will be able to do

A useful study rhythm

Read the explanation, close the book, and draw or explain the idea from memory. Predict each example before running or tracing it. Attempt the chapter exercises, compare your reasoning with the solution manual, and return to the source when an assumption changes.

For a first pass, follow the chapter order. For revision, use the contents and glossary. Assessment answers and exercise solutions are separated from the questions so you can retrieve an answer before seeing it. Internal links and bookmarks work in most PDF readers; the printed page number helps when reading on paper.

Scope and assumptions

Core explanations and original diagrams are available offline. External books, videos, and documentation remain at their publishers’ sites and may require an internet connection or a separate account.

Chapter 01

From source file to running program

Make the build process visible before adding language complexity.

By the end of this chapter
  • Compile and run a C++17 program
  • Separate compiler, linker, and runtime failures

The tools perform different jobs

A C++ program begins as text, not as an executable. Save a source file with a .cpp extension and ask a compiler to translate it. The build also connects your compiled code to library code. The operating system then starts the executable. These are separate events, so a successful build does not prove that the program will calculate the correct answer.

Treat the first compiler error as a clue about structure. A missing closing brace can cause later lines to produce confusing messages. Fix the earliest meaningful error, build again, and observe what changed. A linker error about an undefined reference usually means a required definition was not provided to the final build. A runtime failure happens after a program has already been built.

For the examples in this book, use a compiler that supports C++17. GCC and Clang accept -std=c++17. Visual Studio uses a different command-line syntax. The command shown below is for a Unix-like shell with a compiler available as c++. An editor can run that command for you, but learning its parts makes editor problems much easier to diagnose.

Save as hello.cpp, compile, then run C++17 · hello.cpp
#include <iostream>
int main() {
    std::cout << "OpenLearning\n";
}
// Shell commands, not C++ statements:
// c++ -std=c++17 -Wall -Wextra -pedantic hello.cpp -o hello
// ./hello
Expected result
OpenLearning
A build is a pipelineSource is translated into object code; the linker combines definitions into an executable; the operating system starts it.Source filesText that expresses the programCompilerChecks and translates each translation unitLinkerConnects definitions and librariesExecutableA program the operating system can start
A build is a pipeline. Source is translated into object code; the linker combines definitions into an executable; the operating system starts it.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [2] GCC warning options · [6] CMake tutorial

A repeatable working loop

A useful learning loop is predict, build, run, explain, and change. Before running a small program, write the expected output. If the output differs, keep both the expectation and the observation. The gap tells you which mental model needs work. Random editing may produce the desired output once while leaving the original misunderstanding intact.

Warnings are not all possible mistakes, and -Wall does not literally enable every warning. Start with a practical warning set and investigate its messages. Do not silence a warning merely to obtain a clean screen. An implicit conversion, unused variable, or suspicious comparison often reveals that your program expresses a different idea from the one you intended.

Keep each chapter's complete example in a separate directory. This avoids accidentally compiling several main functions into one executable. Record the command and compiler version beside a bug report. For a multi-file project, learn a build tool such as CMake after you understand a direct compiler invocation. The build tool records the dependency graph; it does not replace the compiler or make incorrect source code correct.

Go deeper: [2] GCC warning options · [6] CMake tutorial

Keep these ideas

  • Keep build, link, and runtime errors distinct.
  • A repeatable command is part of a reproducible example.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

1.1 · Practice task

Introduce a missing semicolon, then restore it. Which stage reports the error?

Hint: Do not run an old executable after a failed build.

Read the worked solution

1.2 · Practice task

Explain why changing a header may require rebuilding several files.

Hint: A translation unit includes the declarations it uses.

Read the worked solution

Chapter 02

Values, types, and honest arithmetic

Use types to express meaning and expose assumptions.

By the end of this chapter
  • Distinguish integer and floating-point arithmetic
  • Avoid uninitialized values and narrowing conversions

Types are part of the calculation

A type describes the values an object can represent and the operations that make sense for it. An int is useful for small whole-number calculations, a double for approximate real-number calculations, and bool for a truth value. A character and a string are different types. A type name does not automatically state the real-world unit, so document whether a quantity is bytes, seconds, cents, or meters.

Initialize variables when they are created. Reading an uninitialized local integer is not a way to obtain a random number; it is an error with undefined behavior. Braced initialization is a useful default because it rejects many narrowing conversions. The compiler can reject int count{2.7}, making the lost fraction explicit rather than silently accepting a different quantity.

Integer division discards the fractional part toward zero. The expression 7 / 2 produces 3 because both operands are integers. Assigning that result to a double afterward does not recover the lost fraction. Convert an operand before division when a fractional result is intended. Before dividing, also decide what a zero denominator means in the domain.

The types of the operands decide the operation C++17
#include <iostream>
int main() {
    int completed{7};
    int sessions{2};
    double average = static_cast<double>(completed) / sessions;
    std::cout << completed / sessions << '\n';
    std::cout << average << '\n';
}
Expected result
3
3.5

Go deeper: [8] C++ built-in types

Boundaries and representation

Integer types have finite ranges. Signed integer overflow is undefined behavior; unsigned arithmetic wraps modulo its range. Neither fact makes unchecked financial or size calculations acceptable. Check a boundary before an operation when the input can approach the limit. In particular, multiplying before comparing can overflow before your comparison has a chance to protect anything.

Floating-point numbers represent a finite set of approximations. The fact that a decimal value looks short on a screen does not mean it has an exact binary representation. For money, a small teaching program can use integer minor units such as cents and an explicit currency. That design still needs policies for rounding, overflow, tax rules, and currencies whose minor units differ.

Use auto when the initializer makes the type obvious or when spelling a long iterator type would add noise. It does not remove the type: auto n = 4 deduces an integer, while auto n = 4.0 deduces a double. Prefer meaningful names over clever type tricks. A well-named variable plus a straightforward expression is easier to review than a compact expression that mixes units and conversions.

Go deeper: [8] C++ built-in types · [5] Clang UndefinedBehaviorSanitizer

Keep these ideas

  • Initialize every local value before use.
  • Choose units and boundary behavior before choosing a numeric type.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

2.1 · Practice task

Why does double x = 5 / 2 produce 2 rather than 2.5?

Hint: Look at the operands before the assignment.

Read the worked solution

2.2 · Practice task

Represent a book price of 129.99 and a quantity of three without floating-point money.

Hint: Name the minor unit.

Read the worked solution

Chapter 03

Control flow and functions that say what they do

Turn a calculation into a small, testable contract.

By the end of this chapter
  • Trace branches and loops
  • Separate returned results from input and display

Trace the path, not just the final line

A branch chooses which statement to execute next. A loop repeats a section until its rule says to stop. Read a loop by writing down its initial state, its condition, its body, and its state change. If the state never approaches a stopping condition, a while loop can run indefinitely. An off-by-one error usually means the chosen interval was never made precise.

Half-open intervals are common in C++: begin is included and end is excluded. For three elements, the valid indexes are zero, one, and two. The condition index < size expresses that interval. The condition index <= size includes one invalid position. Prefer a range-based for loop when you only need each value and do not need its position.

A function gives a useful operation a name. Parameters describe required inputs; its return value describes a result. Keep reading from the terminal and printing messages outside a calculation when possible. A function that computes a total should be reusable in a command-line tool, a test, or a graphical interface without requiring a human to type anything.

A calculation with no input/output dependency C++17
#include <cstddef>
#include <iostream>
#include <vector>
std::size_t count_at_least(const std::vector<int>& values, int limit) {
    std::size_t count{0};
    for (int value : values) {
        if (value >= limit) { ++count; }
    }
    return count;
}
int main() {
    std::cout << count_at_least({4, 8, 8}, 8) << '\n';
    std::cout << count_at_least({}, 8) << '\n';
}
Expected result
2
0

Go deeper: [19] A Tour of C++: author information and samples · [1] C++ Core Guidelines

Contracts make small functions dependable

A useful function contract answers three questions: what inputs are accepted, what result is promised, and what happens when the promise cannot be met? The name count_at_least suggests that equality is included, but a test for a value exactly equal to the limit makes that meaning concrete. The empty vector should return zero because it contains no qualifying values.

A loop invariant is a fact that remains true while a loop progresses. In this example, count equals the number of qualifying values visited so far. Before the first iteration, no values have been visited and count is zero. Each iteration preserves the statement by adding one exactly when the current value qualifies. At the end, every value has been visited, so the invariant describes the final answer.

Avoid using global mutable variables to pass results between functions. Hidden state makes repeated calls depend on earlier calls, which complicates tests and reuse. It is fine for a function to modify an object when that is the operation's explicit purpose; make that purpose visible in its name and parameter types. Small, explicit contracts are the starting point for larger reliable programs.

Go deeper: [1] C++ Core Guidelines

Keep these ideas

  • Use a half-open interval when indexing.
  • Test a boundary, not only a typical input.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

3.1 · Practice task

Change the example to count values strictly above the limit. What must change besides the code?

Hint: Compare the name and equality boundary.

Read the worked solution

3.2 · Practice task

Trace count_at_least({2, 5, 1}, 3) one iteration at a time.

Hint: Record visited values and count.

Read the worked solution

Chapter 04

References, const, and borrowing

Explain who may change an object without confusing that with ownership.

By the end of this chapter
  • Distinguish value, reference, and const reference parameters
  • Recognize a dangling reference

A reference is another way to reach an object

Passing an int by value creates a separate parameter value. Changing that parameter does not change the caller's integer. Passing by non-const reference lets the function operate on the caller's object. A const reference lets the function read through that reference without modifying the object through it. These choices express an interface decision, not merely a performance trick.

A reference must refer to an object when initialized and cannot later be reseated to refer to another object. Assignment through a reference changes the referred-to object. A pointer can represent a missing object with nullptr and can be assigned a different address. Choose a pointer when optional presence is part of the contract; otherwise a reference often expresses required presence more clearly.

Neither a raw reference nor a raw pointer normally owns its target. The owner must keep the target alive for the whole borrowing period. Returning a reference to a local variable is wrong because the local object is destroyed when the function returns. The reference's existence does not extend that object's lifetime.

Copying a value and borrowing a value C++17
#include <iostream>
int change_copy(int value) { value = 90; return value; }
void add_one(int& value) { ++value; }
int read(const int& value) { return value; }
int main() {
    int score{4};
    std::cout << change_copy(score) << '\n';
    add_one(score);
    std::cout << read(score) << '\n';
}
Expected result
90
5
An owner and two observersThe vector owns its elements. References can observe an element only while that element remains alive at a valid location.OwnerControls an object and its lifetimeBorrowed referenceProvides access without owning the objectOperationMust finish before the borrow becomes invalid
An owner and two observers. The vector owns its elements. References can observe an element only while that element remains alive at a valid location.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [9] C++ references · [1] C++ Core Guidelines

Const protects an access path, not every possible alias

Const is an important promise, but it is specific. A const reference prevents modification through that access path. Another non-const alias may still modify an originally non-const object. That is why a const reference alone is not a concurrency guarantee. Similarly, a const pointer and a pointer to const mean different things: one constrains reassignment of the pointer, the other constrains access to the pointed-to value.

Do not return a borrowed object just to avoid an imagined expensive copy. Returning a value is often clearer, and modern C++ can construct results directly in their destination in many cases. Returning a local std::string by value is a normal safe design. Returning a std::string_view into that same local string is not: the view is non-owning and would outlive its characters.

When reading unfamiliar code, draw two separate annotations: where the object lives and which names can reach it. Then identify operations that can destroy, replace, or relocate it. This catches many lifetime mistakes earlier than staring at pointer syntax. Borrowing is safe only when the interface and the surrounding lifetime agree.

Parameter formMeaning for a normal callOwnership
T valueUse a separate parameter valueA value is copied or moved into the parameter
const T& valueRead the existing object during a valid borrowNo ownership transfer
T& valueMay modify the existing objectNo ownership transfer
std::unique_ptr<T> valueReceive exclusive ownershipOwnership is transferred by a move

Go deeper: [9] C++ references · [10] std::vector reference · [1] C++ Core Guidelines

Keep these ideas

  • Borrowing and ownership answer different questions.
  • Const is not a lifetime extension or a locking mechanism.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

4.1 · Practice task

Why is returning const int& from a function that creates a local int still unsafe?

Hint: Const controls mutation, not lifetime.

Read the worked solution

4.2 · Practice task

Choose parameter forms for incrementing a counter and reading a large vector.

Hint: Make the intended effect visible.

Read the worked solution

Chapter 05

Strings, vectors, and container choices

Let standard containers manage ordinary storage.

By the end of this chapter
  • Use vector size and checked access correctly
  • Choose ordered and hash-based lookup deliberately

A vector is a growing sequence, not an infinite array

A std::vector stores a sequence of elements and manages the storage needed for them. Its size is the number of constructed elements. Its capacity describes how many elements can fit before storage must grow. reserve changes capacity when necessary; it does not create elements. resize changes size and constructs or removes elements as required.

Use push_back to append an element. Use at when checked indexing is useful: it throws an exception for an index outside the current size. Operator [] does not perform the same required bounds check. Neither form makes a logically wrong index correct. Often a range-based loop expresses the operation without needing an index at all.

When a vector grows beyond its capacity, it can allocate new storage and move or copy its elements. Pointers, references, and iterators into the old storage can become invalid. Even without reallocation, insertion or erasure can invalidate positions at or after the affected point. Consult the specific operation's rules instead of assuming that every container behaves the same way.

Capacity is not size C++17
#include <iostream>
#include <vector>
int main() {
    std::vector<int> scores;
    scores.reserve(10);
    scores.push_back(6);
    scores.push_back(9);
    std::cout << scores.size() << '\n';
    std::cout << scores.at(1) << '\n';
}
Expected result
2
9
Size and spare capacityOnly the first two positions contain elements; remaining reserved storage does not make additional indexes valid.Constructed elementsIndexes 0 and 1 are valid; size is 2Reserved storageSpace may exist for later elementsAppend operationConstructs another element and increases size
Size and spare capacity. Only the first two positions contain elements; remaining reserved storage does not make additional indexes valid.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [10] std::vector reference · [3] libstdc++ debug mode

Choose a container for the operation you need

A std::string owns a sequence of characters. Its length is not necessarily the number of user-perceived characters in Unicode text. An introductory ASCII parser can process bytes, but a production internationalized editor needs a richer text model. Be explicit about the scope of a text example rather than silently promising universal language handling.

Use std::map when sorted keys and ordered traversal are part of the requirement. Use std::unordered_map when average-case hash lookup fits the problem and ordering is not required. A hash table does not promise that its printed order will remain stable across runs or implementations. Sorting the final result before display can make a report deterministic without changing how it was collected.

Start with vector for a normal sequence unless another operation justifies a different choice. A linked list is not automatically faster because insertion sounds cheap: locating the insertion point and accessing scattered memory also cost time. Think about the whole workload, its size, and its access pattern. Measure a representative program before replacing a straightforward container with a more complicated structure.

ContainerUseful starting requirementDo not assume
vectorOrdered sequence and random accessBorrowed element addresses survive growth
mapKeys traversed in sorted orderAll operations have constant cost
unordered_mapAverage-case hash lookupIteration gives a stable display order
stringOwned character sequenceByte count equals visible character count

Go deeper: [10] std::vector reference · [11] Standard-library algorithms · [19] A Tour of C++: author information and samples

Keep these ideas

  • Capacity and size are different contracts.
  • Invalidation is an operation-specific rule.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

5.1 · Practice task

What is wrong with reserving ten elements and then assigning values[5] before any push_back?

Hint: Check size rather than capacity.

Read the worked solution

5.2 · Practice task

Design a deterministic word-frequency display using a hash table.

Hint: Separate collection from presentation.

Read the worked solution

Chapter 06

Classes that keep their promises

Make invalid state difficult to construct and easy to detect.

By the end of this chapter
  • Define an invariant and protect it
  • Use constructors and const member functions

A class is a boundary around a rule

A class becomes useful when some data must follow a rule over time. A reading goal might require a nonnegative page count. A reservation might require a start time before its end time. State the rule in plain language first; then identify every operation that could break it. A collection of public fields with unrelated getters does not automatically protect anything.

A constructor establishes the object's initial valid state. If the state cannot be established, construction should fail rather than leaving a partially usable object that callers must remember to inspect. A constructor can validate and throw a specific exception. Every successfully constructed object should then satisfy the invariant, simplifying the assumptions made by member functions.

Keep representation private when unrestricted changes would violate the rule. Expose meaningful operations such as add_pages rather than a setter for every field. A getter that only reads the object should normally be a const member function. This makes the interface usable through const objects and communicates that observation is different from modification.

A small class with one explicit invariant C++17
#include <iostream>
#include <stdexcept>
class ReadingGoal {
    int pages_;
public:
    explicit ReadingGoal(int pages) : pages_{pages} {
        if (pages < 0 || pages > 1000000) throw std::invalid_argument("invalid page count");
    }
    int pages() const { return pages_; }
    void add_pages(int extra) {
        if (extra < 0 || extra > 1000000 - pages_)
            throw std::invalid_argument("invalid addition");
        pages_ += extra;
    }
};
int main() {
    ReadingGoal goal{12};
    goal.add_pages(3);
    std::cout << goal.pages() << '\n';
}
Expected result
15

Go deeper: [1] C++ Core Guidelines · [19] A Tour of C++: author information and samples

Prefer a small honest interface

The class uses a teaching bound of one million pages. Construction and addition both enforce that bound, so a caller can rely on it after any successful operation. The addition check uses subtraction before addition, avoiding an intermediate result outside the allowed range. This illustrates why constructor and mutator behavior should be reviewed together: an invariant is only as strong as the least careful public entry point.

A struct and a class can both have member functions and enforce rules. Their default access differs: struct members start public and class members start private. Use a struct for a simple aggregate when independent public values are genuinely acceptable. Use a class boundary when operations must coordinate to preserve a relationship. The choice is about the contract, not a hierarchy of professional-looking syntax.

Do not turn every noun into a class. A pure conversion may be clearer as a function; a record with no behavior may be clearer as an aggregate. When a class is justified, keep its responsibilities narrow enough to explain without the word and. A class that parses files, stores inventory, prints reports, and sends notifications will be hard to test because a change in any one responsibility can affect the others.

Go deeper: [1] C++ Core Guidelines · [19] A Tour of C++: author information and samples

Keep these ideas

  • An invariant must hold after construction and every public operation.
  • Choose classes to protect rules, not merely to group nouns.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

6.1 · Practice task

Test that ReadingGoal preserves its 0 through 1,000,000 invariant at construction and addition boundaries.

Hint: Check construction and mutation against the same bound.

Read the worked solution

6.2 · Practice task

Would a coordinate pair always need private setters and a constructor?

Hint: Ask what rule must be preserved.

Read the worked solution

Chapter 07

Lifetime and RAII: cleanup you can rely on

Connect resources to objects whose lifetime is explicit.

By the end of this chapter
  • Trace construction and destruction order
  • Use standard resource-owning objects instead of manual cleanup

Resources need a responsible owner

A resource is something a program acquires and must eventually release: memory, a file handle, a lock, or a network connection. The difficult part of manual cleanup is not writing a close call once. It is ensuring the close happens on every return path, every exception path, and every future maintenance path, exactly when ownership ends.

RAII ties responsibility for a resource to an object's lifetime. A resource-owning object's constructor acquires or receives the resource; its destructor releases it. When a local object leaves scope, its destructor runs. During normal exception unwinding, destructors for already constructed local objects also run. This lets cleanup follow the structure of the program rather than a programmer's memory of all possible exits.

Use standard owners such as std::string, std::vector, std::ifstream, std::unique_ptr, and std::lock_guard. These types each represent a specific responsibility. The important habit is to find or create the right owner at acquisition time, rather than leave an unowned resource waiting for a later cleanup decision.

Observe the order of lifetime events C++17
#include <iostream>
#include <string>
struct Trace {
    std::string name;
    explicit Trace(std::string value) : name{value} {
        std::cout << "start " << name << '\n';
    }
    ~Trace() { std::cout << "end " << name << '\n'; }
};
int main() {
    Trace outer{"outer"};
    { Trace inner{"inner"}; }
    std::cout << "between\n";
}
Expected result
start outer
start inner
end inner
between
end outer
An owned resource follows scopeAcquisition is represented by a local owner. Work can return or throw; normal scope exit and stack unwinding destroy that owner.Construct ownerAcquire responsibility for the resourceUse resourcePerform work through a valid ownerLeave scopeNormal return or exception unwindingDestroy ownerRelease the resource once
An owned resource follows scope. Acquisition is represented by a local owner. Work can return or throw; normal scope exit and stack unwinding destroy that owner.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [1] C++ Core Guidelines · [16] Object lifetime and RAII

Destruction is not a place to gamble

A destructor should not let an exception escape during stack unwinding. A second escaping exception can terminate the program. If a close operation can report a useful failure, provide an explicit operation that callers can invoke while they can still handle it; keep destruction as reliable final cleanup. Some failures still cannot be recovered from, so define the policy rather than hiding it.

RAII is often incorrectly summarized as stack allocation. A resource owner can itself be a member of another object or be dynamically allocated. The useful property is that ownership forms a chain with a defined end. A vector owns its elements, and each element may own another resource. Destroying the vector then destroys the elements and follows those responsibility chains.

Abnormal process termination, power loss, and certain fatal conditions do not provide ordinary C++ stack unwinding. RAII therefore does not make durable storage crash-safe or distributed operations atomic. A file stream can close properly while a half-written application record remains invalid. Resource lifetime, transaction design, and recovery are related concerns, but they solve different failures.

Go deeper: [1] C++ Core Guidelines · [16] Object lifetime and RAII

Keep these ideas

  • Acquire resources directly into owners.
  • Automatic cleanup is not the same as crash-safe persistence.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

7.1 · Practice task

Why is a manual unlock at the end of a function fragile?

Hint: Consider an early return and an exception.

Read the worked solution

7.2 · Practice task

A file stream closes automatically. Does that guarantee a complete saved report after a power failure?

Hint: Separate resource release from durability.

Read the worked solution

Chapter 08

Copy, move, and value semantics

Predict whether objects are independent and who keeps resources.

By the end of this chapter
  • Explain copying versus moving without myths
  • Prefer the rule of zero for ordinary classes

A copy should have a clear meaning

Value semantics means that ordinary use of a type behaves like working with values: copying creates another value, and changing one does not unexpectedly change the other. A copied std::vector<int> has independent elements. A vector of pointers copies pointer values, however, so the pointed-to objects may still be shared. The container cannot invent a deep-copy policy for the domain.

A class built entirely from well-behaved value members can often use compiler-generated special member functions. This is the rule of zero: let members such as vector and string manage their own resources, so your class does not manually implement a destructor, copy operation, or move operation. The design reduces the number of lifetime cases you must reason about.

Moving permits resources to be transferred from one object to another when the source's current value is no longer needed. std::move is a cast that allows move-enabled overloads to be selected; it does not itself relocate bytes or empty an object. The actual operation depends on the receiving function or constructor and the type's available operations.

Copies are independent; moved-from strings stay valid C++17
#include <iostream>
#include <string>
#include <utility>
#include <vector>
int main() {
    std::vector<int> first{1, 2};
    auto second = first;
    second.push_back(3);
    std::cout << first.size() << ' ' << second.size() << '\n';
    std::string source{"chapter"};
    std::string destination = std::move(source);
    source = "reused";
    std::cout << destination << ' ' << source << '\n';
}
Expected result
2 3
chapter reused
Copy and move express different intentionsCopy keeps two independent vector values. Move can transfer a resource to a destination while the original object remains valid but with a type-defined state.CopyKeep a separate source valueMoveAllow transfer from anexpendable valueBorrowUse an existing value withoutowning it
Copy and move express different intentions. Copy keeps two independent vector values. Move can transfer a resource to a destination while the original object remains valid but with a type-defined state.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [15] std::unique_ptr reference · [1] C++ Core Guidelines · [18] Copy constructors and copy assignment

Do not build an optimization on an assumed source state

Standard-library moved-from objects are generally valid but in an unspecified state unless a stronger promise is documented for the particular operation. You can destroy or assign to them, and you can call operations whose preconditions hold. Do not write a test that assumes a moved-from string is always empty. Its observed state on one library is not the portable contract.

Some owners should not be copied. A unique_ptr represents exclusive ownership, so copying it is disabled. Moving it transfers that ownership and leaves the moved-from unique_ptr empty. A shared_ptr has a different meaning: copying it shares responsibility for the same object. Choosing shared_ptr merely to avoid thinking about lifetime can create cycles, surprising mutation, and unclear architecture.

If you manually manage a resource, the destructor, copy operations, and move operations must agree about ownership. A shallow copy of an owning raw pointer can cause two destructors to release the same resource. Prefer replacing that pointer with a standard owner before writing a custom rule-of-five implementation. Advanced ownership machinery is worthwhile only when the simpler ownership model cannot express the requirement.

Go deeper: [15] std::unique_ptr reference · [1] C++ Core Guidelines · [18] Copy constructors and copy assignment · [20] CppCon 2022: C++ Value Semantics

Keep these ideas

  • std::move enables an operation; it does not itself move.
  • Prefer ordinary value members and the rule of zero.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

8.1 · Practice task

Why can copying vector<int*> still produce shared mutation?

Hint: Distinguish copying the pointer from copying its target.

Read the worked solution

8.2 · Practice task

A moved-from string prints empty on your machine. Can a portable test require that?

Hint: Look for a documented postcondition.

Read the worked solution

Chapter 09

Smart pointers and ownership maps

Make sharing a deliberate relationship rather than a convenient default.

By the end of this chapter
  • Use unique_ptr for exclusive dynamic ownership
  • Recognize shared ownership cycles and observer lifetimes

Dynamic lifetime is a requirement to justify

A local value is often the simplest correct object. Use dynamic ownership when the object genuinely needs a lifetime or polymorphic representation that cannot be expressed conveniently as an ordinary value member. The word dynamic does not mean professional or fast. Every added lifetime relationship is another fact that a reader and a test must understand.

A unique_ptr owns one dynamically allocated object exclusively. make_unique creates the object and immediately places responsibility into the owner. The owner cannot be copied but can be moved. Pass a reference when a function only needs temporary access; pass or return a unique_ptr when ownership itself crosses the interface. These signatures tell callers substantially different stories.

A shared_ptr allows multiple owners of the same object. The object is destroyed when the last owning shared_ptr releases it. Its reference count does not automatically make access to the object thread-safe. Two shared owners can still race while changing the object's fields. Memory lifetime and synchronization must be considered separately.

Ownership can transfer; an observer only borrows C++17
#include <iostream>
#include <memory>
#include <string>
struct Note { std::string title; };
void show(const Note& note) { std::cout << note.title << '\n'; }
std::unique_ptr<Note> make_note() {
    return std::make_unique<Note>(Note{"Ownership"});
}
int main() {
    auto owner = make_note();
    show(*owner);
    auto next_owner = std::move(owner);
    std::cout << std::boolalpha << (owner == nullptr) << '\n';
}
Expected result
Ownership
true

Go deeper: [15] std::unique_ptr reference · [1] C++ Core Guidelines · [17] Thread safety in the C++ standard library

Draw the responsibility graph

An ownership diagram should answer who is responsible for destruction and which edges merely observe. A parent can exclusively own a child while the child keeps a non-owning link back to the parent, provided the parent outlives that observation. If both directions are shared owning pointers, the reference counts may never reach zero, creating a cycle even after the application loses its entry point.

Use weak_ptr when an observation must refer to a shared-owned object without extending its lifetime. Locking a weak_ptr attempts to obtain a temporary shared owner; failure means the object no longer exists. Do not dereference a previously obtained raw pointer after separately checking a weak_ptr and then discarding the temporary owner. Keep the owner for the entire operation that needs the object.

Ownership is part of a design review. Ask whether the relationship is a value, an exclusive child, a temporary borrow, or genuinely shared lifetime. Write the answer before selecting a smart pointer type. This avoids replacing every raw pointer with shared_ptr and preserving the same unclear model under more complicated syntax.

An explicit ownership relationshipThe application owns a repository, the repository owns notes, and a viewer borrows access without extending a note’s lifetime.ApplicationOwns the repository lifetimeRepositoryOwns its notesViewer operationBorrows one note during a call
An explicit ownership relationship. The application owns a repository, the repository owns notes, and a viewer borrows access without extending a note’s lifetime.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [1] C++ Core Guidelines · [15] std::unique_ptr reference

Keep these ideas

  • Choose a lifetime model before choosing a pointer.
  • A shared reference count does not protect mutable state.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

9.1 · Practice task

A function only prints a Note. Should it take unique_ptr<Note> by value?

Hint: Ask whether printing transfers responsibility.

Read the worked solution

9.2 · Practice task

Explain why two shared_ptr objects pointing at each other may leak.

Hint: Trace what keeps each reference count positive.

Read the worked solution

Chapter 10

Algorithms, iterators, and small lambdas

Describe an operation at the level of its intent.

By the end of this chapter
  • Use half-open iterator ranges
  • Capture lambda state deliberately

Algorithms separate traversal from the operation

A standard algorithm performs a familiar operation over a range: find a value, count matching items, sort a sequence, or transform values. Instead of rewriting the loop each time, provide the range and the rule. This makes the operation easier to recognize and reduces the number of index calculations scattered through a program.

A range represented by begin and end is half-open. The end iterator is a boundary, not an element to dereference. An empty vector has begin equal to end. Many algorithms naturally handle that empty range, but an operation that returns an iterator can still return end to indicate that nothing was found. Check that result before using it.

Different algorithms require different iterator capabilities. Sorting needs random-access iterators, so std::sort works with vector but not with every container. An algorithm also does not automatically protect against changing the container in ways that invalidate the range while it runs. Know both the algorithm's preconditions and the container's mutation rules.

Sort and count with small predicates C++17
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
    std::vector<int> minutes{25, 10, 40, 15};
    std::sort(minutes.begin(), minutes.end());
    int limit{20};
    auto count = std::count_if(minutes.begin(), minutes.end(),
        [limit](int value) { return value >= limit; });
    for (int value : minutes) std::cout << value << ' ';
    std::cout << "\ncount=" << count << '\n';
}
Expected result
10 15 25 40 
count=2

Go deeper: [11] Standard-library algorithms · [10] std::vector reference

A lambda captures a relationship to surrounding state

A lambda is a function object written near its use. Its parameter list describes each input supplied by the algorithm. Its capture list describes the surrounding values or references it keeps. Capture a threshold by value when the lambda should use that threshold's current value independently. Capture by reference only when access to the existing object is intended and its lifetime is sufficient.

A lambda stored for later use can outlive local variables it captures by reference. Returning such a lambda can therefore return a future dangling reference. This is the same lifetime problem seen with ordinary references, even though square-bracket syntax may make it look different. A short-lived algorithm callback and a stored asynchronous callback need different lifetime analysis.

For sorting, the comparison must follow a consistent strict ordering. Using <= as a less-than comparator is incorrect because an item would compare before itself. A comparator whose answer depends on changing external state is also dangerous. Write the ordering in plain language, test equal keys, and decide whether equal items need their original relative order preserved. If they do, consider stable_sort and its documented tradeoffs.

Worked example · Sorting study sessions by duration

  1. Given durations 25, 10, 40, and 15, ascending sorting produces 10, 15, 25, 40.
  2. The captured threshold is 20, so exactly 25 and 40 satisfy the predicate.
  3. The count algorithm reads the sequence and returns two; it does not remove shorter sessions.

Result: Sorting and selection are separate operations with separate effects.

Go deeper: [12] Lambda expressions · [11] Standard-library algorithms

Keep these ideas

  • Treat end as a boundary, never a guaranteed element.
  • Captured references have ordinary lifetime obligations.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

10.1 · Practice task

Why should a sort comparator use a < b rather than a <= b?

Hint: Compare an item with itself.

Read the worked solution

10.2 · Practice task

A function returns a lambda that captures its local string by reference. What can fail?

Hint: Compare the local lifetime with the returned callable lifetime.

Read the worked solution

Chapter 11

Templates without mystery

Write one algorithm for a clear family of types.

By the end of this chapter
  • Understand template instantiation
  • State the operations a type must support

A template is a recipe with requirements

A function template describes an operation parameterized by a type. The compiler forms concrete functions for the types that are used. This can remove duplicated logic, but it does not mean that every conceivable type will work. The function body still requires specific operations, such as comparison, copying, or addition.

In C++17, express those requirements in clear documentation and tests, and keep template functions small enough for compiler diagnostics to remain understandable. C++20 concepts can improve how requirements are expressed, but they are outside the executable baseline used here. Do not silently add newer syntax to a program advertised as C++17.

Template definitions generally need to be visible where they are instantiated, which is why many template libraries put definitions in headers. A declaration alone may leave the compiler unable to generate the requested specialization. This differs from the ordinary multi-file pattern in which a non-template function definition can be compiled separately and linked later.

A small template with an explicit behavioral requirement C++17
#include <iostream>
#include <string>
template<class T>
T larger(T first, T second) {
    return first < second ? second : first;
}
int main() {
    std::cout << larger(3, 8) << '\n';
    std::cout << larger(std::string{"ant"}, std::string{"bee"}) << '\n';
}
Expected result
8
bee

Go deeper: [13] C++ templates · [6] CMake tutorial

Generic code still needs semantic tests

The example requires that two values of the same T can be compared with < and that a result can be returned by value. Integer ordering chooses a numeric maximum. String ordering chooses a lexicographic maximum, which is not the longest string or the latest publication date. Syntactic compatibility is not proof that the operation means what a caller expects.

Avoid making a function generic before you have at least a clear use case for the common behavior. Two functions with similar-looking lines may have different error policies, units, or ownership rules. Extracting them into a highly parameterized template too early can hide those meaningful differences behind configuration options.

When a template error is long, find the first line that refers to your call and identify the deduced type. Then ask which operation in the function body that type does not support. Reduce the problem to one small use. This is more productive than treating the entire instantiation trace as a list of unrelated failures. An understandable template is one whose type requirements can be stated in a sentence.

From a recipe to concrete functionsOne template definition is used with two distinct types. Each resulting operation has concrete type checking, and semantic meaning still depends on the chosen type.Template recipeRequires comparable values of the same typeInteger instantiationCompare 3 and 8 numericallyString instantiationCompare ant and bee lexicographically
From a recipe to concrete functions. One template definition is used with two distinct types. Each resulting operation has concrete type checking, and semantic meaning still depends on the chosen type.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [13] C++ templates · [1] C++ Core Guidelines

Keep these ideas

  • Generic code has both type requirements and meaning requirements.
  • Keep the supported language version explicit.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

11.1 · Practice task

Why does larger(3, 8.5) fail to deduce the single T in this example?

Hint: Both parameters request the same template type.

Read the worked solution

11.2 · Practice task

Would larger("cat", "elephant") necessarily compare text content?

Hint: Consider the types of string literals and decay.

Read the worked solution

Chapter 12

Errors, files, and input boundaries

Make failure visible without turning every missing value into a crash.

By the end of this chapter
  • Separate optional absence from malformed input
  • Check stream state and validate before mutation

Define a failure policy for each boundary

Input arrives with fewer guarantees than your internal model. A file may be absent, a line may contain letters where an integer is expected, or a value may be outside the allowed range. Decide which outcomes are normal alternatives and which prevent the operation from fulfilling its contract. A missing search result can be represented by an optional value; an unreadable required configuration may require a reported error.

An exception transfers control to a matching handler while stack unwinding destroys local owners. Catch exceptions where the program can recover, translate them into a useful boundary message, or decide to stop. Catching every failure and continuing with a default value can silently corrupt results. A default average of zero is not an honest replacement for a failed dataset read.

File streams own their handles, but callers still need to check whether opening and reading succeeded. RAII handles cleanup; it does not decide whether an incomplete report should be accepted. After parsing, validate the domain constraints before updating shared program state. This prevents a malformed line from leaving half of a logical operation applied.

Parse one whole integer line without accepting trailing junk C++17
#include <iostream>
#include <optional>
#include <sstream>
#include <string>
std::optional<int> parse_nonnegative(const std::string& text) {
    std::istringstream input{text};
    int value{};
    char extra{};
    if (!(input >> value) || (input >> extra) || value < 0)
        return std::nullopt;
    return value;
}
int main() {
    for (const std::string text : {"12", "12x", "-2"}) {
        auto value = parse_nonnegative(text);
        std::cout << (value ? std::to_string(*value) : "invalid") << '\n';
    }
}
Expected result
12
invalid
invalid

Go deeper: [14] C++ exception handling · [16] Object lifetime and RAII · [19] A Tour of C++: author information and samples

A parser has a narrower promise than a full application

The parser accepts leading and trailing whitespace because formatted stream extraction skips whitespace. It rejects an extra non-whitespace character by attempting to read one more character after the integer. It also rejects negative values and out-of-range integer conversions through stream failure. These details are part of its actual contract, not incidental formatting trivia.

Returning optional<int> explains success or absence but does not say why parsing failed. That is sufficient for a small exercise; a user-facing importer may need an error structure with line number and reason. Add that information deliberately. Do not force callers to reconstruct the reason from an ambiguous zero or an unrelated global error string.

For file processing, first decide whether one malformed row should reject the whole file or be reported while valid rows are retained. Both policies can be reasonable, but they produce different reports and recovery steps. Keep a count of accepted and rejected rows, preserve the original line number, and avoid printing secret or untrusted input blindly. Robustness comes from an explicit policy plus tests of its boundaries.

Go deeper: [14] C++ exception handling · [19] A Tour of C++: author information and samples

Keep these ideas

  • Cleanup and error reporting are separate responsibilities.
  • Never turn malformed input into a plausible value silently.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

12.1 · Practice task

Should an empty search result and a failed file read always use the same failure mechanism?

Hint: Ask whether absence is an expected alternative.

Read the worked solution

12.2 · Practice task

Add tests for the parser’s whitespace and trailing-junk policy.

Hint: Try 12 followed by spaces and then by a letter.

Read the worked solution

Chapter 13

Debugging, tests, and shared-state boundaries

Use tools as evidence and know what they do not prove.

By the end of this chapter
  • Build boundary tests and use sanitizers
  • Recognize a data race and protect a complete invariant

A tool can expose a mistake your examples miss

A test compares an observed result with a stated expectation. Begin with normal cases, then empty inputs, endpoints, malformed inputs, and repeated operations. A test that prints a result for a person to inspect is less reliable than a check that fails clearly. During development, assert can document internal assumptions, but its checks may be disabled when NDEBUG is defined; do not use it as the only validation for untrusted input.

AddressSanitizer and UndefinedBehaviorSanitizer instrument programs to detect selected classes of runtime mistakes. They can reveal out-of-bounds memory access, use-after-free, and certain invalid arithmetic operations while the instrumented program runs. A clean sanitizer run does not prove that every path is safe. Unexecuted paths remain unobserved, and logical mistakes can produce valid machine operations with wrong domain results.

Minimize a failing case before changing architecture. Reduce the input, remove unrelated functions, and retain the failure. A small reproduction makes it easier to distinguish a lifetime error from a parsing error or an incorrect expectation. Keep the new regression test after the fix, so a future edit cannot quietly reintroduce the same behavior.

A basic boundary test executable C++17
#include <cassert>
#include <vector>
int total(const std::vector<int>& values) {
    int result{0};
    for (int value : values) result += value;
    return result;
}
int main() {
    assert(total({}) == 0);
    assert(total({4}) == 4);
    assert(total({2, 3}) == 5);
}
// Build without NDEBUG for these teaching checks.
// clang++ -std=c++17 -g -fsanitize=address,undefined test.cpp -o test
Expected result
No output and exit status 0 when all assertions hold.

Go deeper: [4] Clang AddressSanitizer · [5] Clang UndefinedBehaviorSanitizer · [7] GoogleTest primer

Concurrency adds more than a second loop

Two threads accessing the same memory location can create a data race when at least one access modifies it and the accesses are not properly synchronized. In C++, a data race has undefined behavior. The expression ++counter is not automatically a safe shared operation merely because it occupies one source line. A shared_ptr keeping counter's owner alive does not solve this problem.

A mutex can protect a logical invariant if every relevant access follows the same locking rule. Use a scoped owner such as lock_guard so unlocking follows scope exit. Protect the complete read-check-update operation, not only the final assignment. For example, checking stock outside the lock and decrementing it inside the lock can still oversell when two callers both observe the same earlier quantity.

Do not introduce threads to make a small program look advanced. First measure where time is spent and identify independent work. Thread creation, communication, and synchronization have costs. A correct sequential baseline is easier to reason about and provides a trustworthy result against which a concurrent version can be checked. Advanced lock-free structures and memory ordering require a separate careful study.

Protect the whole transactionRead, validate, and update must share one synchronization boundary when they maintain one invariant.Acquire lockJoin the agreed synchronization protocolRead and validateCheck the current state while protectedUpdate statePreserve the invariant before releasingRelease lockScoped guard ends the protected operation
Protect the whole transaction. Read, validate, and update must share one synchronization boundary when they maintain one invariant.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [17] Thread safety in the C++ standard library · [1] C++ Core Guidelines

Keep these ideas

  • A clean tool run is evidence, not a universal proof.
  • Synchronize an invariant rather than an isolated assignment.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

13.1 · Practice task

Why can checking stock before taking the mutex still be wrong?

Hint: Interleave two callers between the check and update.

Read the worked solution

13.2 · Practice task

A sanitizer run passes. What evidence is still missing?

Hint: Consider coverage and domain meaning.

Read the worked solution

Chapter 14

Capstone: a trustworthy study-log summary

Combine parsing, value types, containers, contracts, and tests in one small program.

By the end of this chapter
  • Build and explain a complete C++17 executable
  • Identify limitations and extend the design safely

Choose a small format and explicit rules

The project receives lines containing a single-word topic and a whole-number duration. A successful line becomes a Session value. Valid durations are one through 480 minutes. A malformed line is rejected rather than converted into zero. Topic totals are capped at one million minutes in this teaching implementation to demonstrate checking before addition. The format is intentionally narrower than a general spreadsheet or CSV parser.

The parser returns an optional Session, so parsing does not change the totals directly. That separation lets a caller choose whether to reject an entire file or keep valid rows and report the invalid ones. The example keeps valid rows and counts rejections. A production importer should attach line numbers and reasons; this version keeps the core data flow visible.

The summarizer receives values and returns a new map. It validates duration again because it is a public calculation that could be called without the parser. This is not random duplicated validation: the parser protects a text boundary, while the summarizer protects its own stated contract. Map traversal gives deterministic topic ordering without a later sorting step.

Keep the three responsibilities separateRaw lines are parsed into validated session values, summarized into totals, then formatted for display. Rejection information follows a separate reporting path.ParseTurn one text line into a Session or rejectionSummarizeCombine valid values with overflow checksReportDisplay deterministic totals and rejected count
Keep the three responsibilities separate. Raw lines are parsed into validated session values, summarized into totals, then formatted for display. Rejection information follows a separate reporting path.Scroll horizontally to read the full diagram on a small screen.
Save, compile, and run the complete capstone C++17 · study_log.cpp
#include <cassert>
#include <iostream>
#include <map>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
struct Session { std::string topic; int minutes; };
std::optional<Session> parse(const std::string& line) {
    std::istringstream input{line};
    Session item;
    char extra{};
    if (!(input >> item.topic >> item.minutes) || (input >> extra))
        return std::nullopt;
    if (item.minutes < 1 || item.minutes > 480) return std::nullopt;
    return item;
}
std::map<std::string, int> summarize(const std::vector<Session>& sessions) {
    std::map<std::string, int> totals;
    for (const auto& session : sessions) {
        if (session.minutes < 1 || session.minutes > 480)
            throw std::invalid_argument("invalid session length");
        int& total = totals[session.topic];
        if (total > 1000000 - session.minutes)
            throw std::overflow_error("topic total is too large");
        total += session.minutes;
    }
    return totals;
}
int main() {
    assert(!parse("python -1"));
    assert(!parse("python 30 extra"));
    assert(!parse("python 481"));
    assert(summarize({}).empty());
    const std::vector<std::string> lines{
        "cpp 25", "networks 40", "cpp 35", "bad -2"};
    std::vector<Session> sessions;
    int rejected{0};
    for (const auto& line : lines) {
        auto session = parse(line);
        if (session) sessions.push_back(*session);
        else ++rejected;
    }
    const auto totals = summarize(sessions);
    assert(totals.at("cpp") == 60);
    assert(totals.at("networks") == 40);
    for (const auto& [topic, minutes] : totals)
        std::cout << topic << ": " << minutes << " min\n";
    std::cout << "rejected: " << rejected << '\n';
}
Expected result
cpp: 60 min
networks: 40 min
rejected: 1

Go deeper: [10] std::vector reference · [11] Standard-library algorithms · [14] C++ exception handling

Explain the result before adding features

The two cpp sessions contain 25 and 35 minutes, giving 60. The networks session contributes 40. The negative duration is rejected, so it contributes neither a topic nor a negative adjustment. The report prints cpp before networks because std::map orders these string keys. The rejected count is one. Those observations should agree with both your hand calculation and the executable output.

Build with warnings, then run a debug build with sanitizers on a compatible compiler. The included assertions check several boundaries, but a complete test set should also cover zero, one, 480, 481, empty lines, missing fields, excess fields, nonnumeric duration, repeated topics, and a total that reaches the cap exactly. Add a test that exceeds the cap and confirms that the operation reports failure instead of wrapping.

Next, introduce a file reader that returns lines while preserving line numbers. Keep it separate from summarize, so calculation tests still need no filesystem. Then improve parser errors with a small result structure. If topic names need spaces, choose a real format and a suitable parser rather than adding fragile splitting rules. If the input becomes enormous, discuss whether retaining every Session is necessary or whether a validated streaming design can preserve the same contract with bounded memory.

This project demonstrates a useful foundation, not all of C++. The next learning steps include iterators in more depth, generic libraries, build-system targets, testing frameworks, profiling, and carefully scoped concurrency. Modern language features should be learned in the context of a concrete problem and a compiler version you can name.

Go deeper: [4] Clang AddressSanitizer · [5] Clang UndefinedBehaviorSanitizer · [6] CMake tutorial · [7] GoogleTest primer

Keep these ideas

  • Parse, calculate, and display are separate seams.
  • A good capstone includes rejected input and boundary tests.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

14.1 · Practice task

Change the policy so any malformed line rejects the whole import. What should happen to previously parsed rows?

Hint: Delay committing a result until validation is complete.

Read the worked solution

14.2 · Practice task

Extend the summary to show the longest session per topic.

Hint: Decide what the empty case means before adding fields.

Read the worked solution

Practice with feedback

Worked solutions

These solutions show a valid line of reasoning. Compare assumptions and intermediate steps, rather than only the final number or output. Other implementations can be equally good when they preserve the stated contract.

Chapter 1 · From source file to running program

Solution 1.1

The compiler reports a syntax error while translating the source. After restoring the semicolon, build again and run the newly produced executable. Running a previous executable would test an earlier program and could hide the failure.

Return to the task

Solution 1.2

Including a header makes its relevant text part of each translation unit during preprocessing. A changed declaration can affect every source file that includes it. A dependency-aware build tool rebuilds those units and relinks the result rather than assuming only the edited file matters.

Return to the task

Chapter 2 · Values, types, and honest arithmetic

Solution 2.1

Both operands are integers, so integer division happens first and produces the integer 2. Conversion then stores 2.0 in x. Use 5.0 / 2 or explicitly convert one operand before division.

Return to the task

Solution 2.2

Store price_cents as 12999 and quantity as 3, then calculate 38997 cents after checking the multiplication range. Format the quotient and remainder when displaying the value. This avoids binary decimal approximation but does not supply currency conversion or business rounding rules.

Return to the task

Chapter 3 · Control flow and functions that say what they do

Solution 3.1

Use > instead of >=, rename the function count_above, and update the equal-to-limit test. A code change without a contract change leaves callers guessing which behavior is intended.

Return to the task

Solution 3.2

Initially count is zero. Visiting 2 leaves it zero; visiting 5 increases it to one; visiting 1 leaves it one. The returned result is one, and the invariant explains why no additional adjustment is necessary after the loop.

Return to the task

Chapter 4 · References, const, and borrowing

Solution 4.1

The local integer is destroyed when the function returns. The returned reference then refers to an object whose lifetime has ended. Const does not revive it or transfer ownership. Return int by value instead.

Return to the task

Solution 4.2

Use int& for an operation whose contract increments the caller’s counter. Use const std::vector<int>& to read an existing large vector without copying it. If a vector must be retained beyond the call, document and represent that ownership separately rather than keeping a borrowed reference accidentally.

Return to the task

Chapter 5 · Strings, vectors, and container choices

Solution 5.1

The vector still has size zero, so index five is outside its constructed elements. Use resize if six elements should exist, or append elements with push_back. Reserving capacity only prepares storage for future growth.

Return to the task

Solution 5.2

Count words in an unordered_map if its average lookup behavior is appropriate. Copy key/count pairs to a vector, sort them by the intended display rule, and print that vector. Never rely on the hash table’s iteration order as an accidental user interface.

Return to the task

Chapter 6 · Classes that keep their promises

Solution 6.1

Reject constructor arguments below zero or above one million. Keep the addition check extra > 1000000 - pages_ before adding, so the calculation does not overflow. Tests should cover both endpoints, an excessive constructor value, and an addition that lands exactly on the maximum.

Return to the task

Solution 6.2

If x and y are independent finite teaching values with no additional rule, a simple aggregate may be enough. If coordinates must stay within a board or use a specific reference system, a class can validate that relationship. Encapsulation should protect a meaningful contract rather than add ceremony to every record.

Return to the task

Chapter 7 · Lifetime and RAII: cleanup you can rely on

Solution 7.1

Any new exit between lock and unlock can leave the mutex locked. A scoped lock object releases the mutex when that scope exits through normal execution or unwinding. The protected invariant still needs careful design; automatic unlocking does not make the protected calculation correct.

Return to the task

Solution 7.2

No. Automatic closing manages the file handle during ordinary lifetime handling. A power failure can interrupt writes or occur before data reaches durable storage. A robust save design may need temporary files, checked errors, a suitable atomic replacement strategy, and explicit durability requirements.

Return to the task

Chapter 8 · Copy, move, and value semantics

Solution 8.1

The vector duplicates its pointer elements. Both vectors’ corresponding pointers can still address the same integer. To obtain independent values, store integers directly or define an explicit deep-copy policy appropriate to the objects and their relationships.

Return to the task

Solution 8.2

No general empty-string postcondition follows from an ordinary string move. Test the destination’s promised value and only use the source in ways allowed by its valid but unspecified state. Reassigning the source before reuse is a simple way to establish a new known value.

Return to the task

Chapter 9 · Smart pointers and ownership maps

Solution 9.1

Usually no. Taking unique_ptr by value consumes ownership, which is unrelated to printing. A const Note& expresses required read-only access during the call. Use a pointer if absence is meaningful and explicitly handled.

Return to the task

Solution 9.2

Each object contains an owning reference to the other, so neither count reaches zero when outside owners disappear. Change one relationship to a non-owning observation where the lifetime model permits it, often using weak_ptr for shared-owned objects. Verify that the remaining owners still express the intended lifetimes.

Return to the task

Chapter 10 · Algorithms, iterators, and small lambdas

Solution 10.1

A strict ordering must not say that a value comes before itself. With <=, equal values compare true in both directions, violating the required comparison contract. The result is not a reliable sorting rule.

Return to the task

Solution 10.2

The local string is destroyed when the function returns, but the callable still refers to it. Capture an owned string value when the callable must retain that text. If sharing an external object is intended, express and enforce that longer lifetime explicitly.

Return to the task

Chapter 11 · Templates without mystery

Solution 11.1

One argument suggests int and the other suggests double. The single template parameter cannot be deduced consistently from both arguments in this call. Convert deliberately or design a different interface after deciding which result type and conversion policy are intended.

Return to the task

Solution 11.2

Do not rely on this template call for text ordering with raw character pointers. Pointer comparisons are not a replacement for string-content comparison. Use std::string values so the operation has the intended string ordering semantics, and separately decide whether ordering or length is the real requirement.

Return to the task

Chapter 12 · Errors, files, and input boundaries

Solution 12.1

No. A search can legitimately find nothing and return an optional result. A required file failing to open may prevent the operation from proceeding and should produce a useful error. The choice depends on the caller’s contract, not a universal rule that exceptions or optionals are always superior.

Return to the task

Solution 12.2

The string " 12 " should produce 12 because surrounding whitespace is permitted. "12x" and "12 7" should fail because another non-whitespace character remains. Empty input should fail. These tests make whole-line parsing distinct from accepting an integer prefix.

Return to the task

Chapter 13 · Debugging, tests, and shared-state boundaries

Solution 13.1

Both callers can observe one remaining item before either locks. They may then decrement in turn and violate the nonnegative-stock invariant. Put the read, availability check, and successful decrement inside the same protected region, and require all competing accesses to follow that rule.

Return to the task

Solution 13.2

Paths not executed by the test have not been observed, and sanitizers do not know the intended business result. Add representative and boundary tests, review ownership and contracts, and test the actual supported configurations. Tools strengthen evidence; they do not replace a correctness argument.

Return to the task

Chapter 14 · Capstone: a trustworthy study-log summary

Solution 14.1

Collect parsed values and errors without publishing totals. If any line is invalid, return an import failure containing the relevant line information and do not replace the previous successful report. If all rows are valid, summarize and publish once. Tests should verify that a valid first line followed by an invalid second line does not produce a partially accepted report.

Return to the task

Solution 14.2

Use a per-topic summary value containing total minutes and maximum session minutes, initialized from the first valid session for that topic. An empty input should produce an empty map, not a fake topic with zero minutes. Test repeated topics with equal and unequal durations, and keep total-overflow validation independent from maximum selection.

Return to the task

Retrieve before you review

Final knowledge check

Choose one answer for each question and write a short reason. Use the explanation to find the assumption or misconception behind an error.

  1. 1. Which stage usually reports a missing function definition after source translation?

    1. The linker
    2. A successful runtime calculation
    3. The text editor’s font renderer
    4. The operating system scheduler
    Check answer and reasoning
  2. 2. What is 9 / 4 when both operands are int?

    1. 2.25
    2. 2
    3. 3
    4. A string
    Check answer and reasoning
  3. 3. Which case most directly checks the inclusive boundary of count_at_least?

    1. A vector much larger than memory
    2. No calls at all
    3. A value exactly equal to the threshold
    4. A different compiler font
    Check answer and reasoning
  4. 4. Does const int& extend the lifetime of a local integer returned by reference?

    1. Always
    2. Only in release builds
    3. Only if the integer is positive
    4. No
    Check answer and reasoning
  5. 5. After reserve(20) on an empty vector, what is its size?

    1. 0
    2. 20
    3. At least 20
    4. Unspecified
    Check answer and reasoning
  6. 6. Where must a class invariant hold?

    1. Only in the destructor
    2. After successful construction and every successful public operation
    3. Only when a debugger is attached
    4. Only for the first object
    Check answer and reasoning
  7. 7. What does RAII primarily connect?

    1. Network retries to server load
    2. Variable names to screen colors
    3. Resource responsibility to object lifetime
    4. Source formatting to execution speed
    Check answer and reasoning
  8. 8. Which statement about std::move is accurate?

    1. It always empties a string
    2. It always allocates new memory
    3. It deletes the source immediately
    4. It permits move-enabled overload selection through a cast
    Check answer and reasoning
  9. 9. Which parameter best expresses temporary required read-only access to a Note?

    1. const Note&
    2. unique_ptr<Note> by value in every case
    3. shared_ptr<Note> to avoid all thought
    4. An owning raw pointer with no policy
    Check answer and reasoning
  10. 10. Why is <= unsuitable as an ordinary ascending sort comparator?

    1. It compiles too quickly
    2. It says an item compares before itself
    3. It cannot compare integers
    4. It always preserves original order
    Check answer and reasoning
  11. 11. A template accepts a type syntactically. What else still matters?

    1. Its spelling length
    2. The editor theme
    3. Whether the operations mean what the domain requires
    4. Whether all variables use auto
    Check answer and reasoning
  12. 12. Why reject 12x when parsing one whole integer line?

    1. All text should be forbidden
    2. Because 12 is negative
    3. Because x needs a separate thread
    4. Because trailing non-whitespace input violates the complete-line contract
    Check answer and reasoning
  13. 13. Where should the availability check and decrement occur for a mutex-protected stock invariant?

    1. Within the same agreed critical section
    2. In unrelated functions with no shared locking rule
    3. Only the final assignment needs protection
    4. Only in a comment
    Check answer and reasoning
  14. 14. Why does summarize validate durations even after parsing?

    1. The parser can never work
    2. The calculation has its own public contract and may receive values from other callers
    3. Map requires every value to be positive automatically
    4. Validation sorts the report
    Check answer and reasoning

Assessment explanations

1. Answer A

The linker

Translation can accept a declaration without its definition. Linking must connect the required definition to the executable.

Revisit the chapter · Return to the question

2. Answer B

2

Integer division discards the fractional part toward zero. A later conversion to double cannot recover it.

Revisit the chapter · Return to the question

3. Answer C

A value exactly equal to the threshold

The equality case distinguishes >= from > and makes the function name’s promise observable.

Revisit the chapter · Return to the question

4. Answer D

No

Const restricts modification through an access path; it does not keep a local object alive after return.

Revisit the chapter · Return to the question

5. Answer A

0

reserve may prepare storage but does not construct twenty elements. Only the capacity promise changes.

Revisit the chapter · Return to the question

6. Answer B

After successful construction and every successful public operation

The interface’s usefulness depends on every public entry point preserving the same rule.

Revisit the chapter · Return to the question

7. Answer C

Resource responsibility to object lifetime

Resource-owning objects release responsibility when their lifetimes end during normal scope handling and unwinding.

Revisit the chapter · Return to the question

8. Answer D

It permits move-enabled overload selection through a cast

The selected operation performs any transfer; std::move by itself does not perform a resource move.

Revisit the chapter · Return to the question

9. Answer A

const Note&

A const reference borrows access without transferring or sharing ownership, provided the target outlives the call.

Revisit the chapter · Return to the question

10. Answer B

It says an item compares before itself

A strict ordering requires that no value precede itself. Equality must not make the comparison true in both directions.

Revisit the chapter · Return to the question

11. Answer C

Whether the operations mean what the domain requires

A string’s ordering and a number’s ordering can both compile while expressing different notions of a maximum.

Revisit the chapter · Return to the question

12. Answer D

Because trailing non-whitespace input violates the complete-line contract

Accepting an integer prefix would silently treat malformed input as a valid complete record.

Revisit the chapter · Return to the question

13. Answer A

Within the same agreed critical section

Another thread must not change the state between the check and update. Every relevant access must follow the same protocol.

Revisit the chapter · Return to the question

14. Answer B

The calculation has its own public contract and may receive values from other callers

A function must protect the assumptions it promises to enforce, regardless of whether one particular caller already checked them.

Revisit the chapter · Return to the question

Glossary

Borrow
Temporary access that does not transfer responsibility for destruction. Chapter
Capacity
The number of elements a vector can hold before storage growth is required. Chapter
Constructor
An operation that establishes a newly created object’s state. Chapter
Critical section
A region whose operations follow a synchronization rule to protect shared state. Chapter
Dangling reference
A reference whose target is no longer alive or otherwise valid to access. Chapter
Data race
Unsynchronized conflicting accesses from threads, with at least one write. Chapter
Destructor
An operation run as an object’s lifetime ends, commonly releasing owned resources. Chapter
Exclusive ownership
A relationship with one responsible owner, expressed by unique_ptr for a dynamically owned object. Chapter
Half-open range
A range that includes its beginning and excludes its ending boundary. Chapter
Initialization
Establishing an object’s initial value when its lifetime begins. Chapter
Invalidation
An operation making a previously obtained iterator, pointer, or reference unsuitable for its previous use. Chapter
Invariant
A rule that remains true at specified program boundaries. Chapter
Iterator
An abstraction for referring to a position in a sequence or range. Chapter
Lambda capture
The values or references a lambda keeps from its surrounding scope. Chapter
Linker
The tool that connects compiled definitions and libraries into a final program. Chapter
Move operation
An operation permitted to transfer resources from an expendable source. Chapter
Narrowing
A conversion that can lose representable information, rejected in many braced-initialization cases. Chapter
Optional value
A result type that explicitly contains either a value or no value. Chapter
Parameter
A named input in a function declaration or definition. Chapter
RAII
Resource management that ties responsibility to object lifetime. Chapter
Reference
A non-reseatable access path bound to an object. Chapter
Rule of zero
Prefer members that manage their own resources so custom special member functions are unnecessary. Chapter
Shared ownership
A relationship where multiple owners collectively keep an object alive. Chapter
Size
The number of constructed elements currently in a container. Chapter
Stack unwinding
Destruction of applicable local objects while an exception travels to a handler. Chapter
Template instantiation
Formation of concrete code from a template and specific arguments. Chapter
Translation unit
The source seen by the compiler after preprocessing a source file and its includes. Chapter
Undefined behavior
A situation for which the language imposes no required behavior; a plausible output is not a safety guarantee. Chapter
Value semantics
Behavior where copying a value normally gives independent value-like use. Chapter
Weak observation
A non-owning relationship to a shared-owned object, checked through weak_ptr. Chapter

Read and watch with a purpose

Reading and video library

Use the chapter source links to choose a relevant next explanation. Each entry below states what it adds. Documentation links may evolve; edition 2026.12 records the assumptions used here.

  1. C++ Core Guidelines

    ISO C++ Foundation community · docs

    Design rules for ownership, interfaces, classes, and concurrency; a living document, with examples that may use newer standards.

    https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
  2. GCC warning options

    GCC project · docs

    Check warning meanings and command-line behavior for the installed GCC release.

    https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
  3. libstdc++ debug mode

    GCC project · docs

    Understand checked debug containers and the compatibility limits of debug-mode builds.

    https://gcc.gnu.org/onlinedocs/libstdc++/manual/debug_mode_using.html
  4. Clang AddressSanitizer

    LLVM project · docs

    Build an instrumented executable and understand the classes of memory defects it can detect.

    https://clang.llvm.org/docs/AddressSanitizer.html
  5. Clang UndefinedBehaviorSanitizer

    LLVM project · docs

    Investigate selected undefined operations without treating one successful run as a proof.

    https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html
  6. CMake tutorial

    Kitware / CMake · docs

    Grow from a direct compiler command to dependency-aware project targets.

    https://cmake.org/cmake/help/latest/guide/tutorial/index.html
  7. GoogleTest primer

    GoogleTest project · docs

    Learn a full testing framework after the standalone teaching assertions.

    https://google.github.io/googletest/primer.html
  8. C++ built-in types

    Microsoft · docs

    Verify fundamental-type categories and implementation-specific details.

    https://learn.microsoft.com/en-us/cpp/cpp/fundamental-types-cpp?view=msvc-170
  9. C++ references

    Microsoft · docs

    Review reference binding and distinguish references from reseatable pointers.

    https://learn.microsoft.com/en-us/cpp/cpp/references-cpp?view=msvc-170
  10. std::vector reference

    Microsoft · docs

    Look up size, capacity, checked access, and operation-specific invalidation.

    https://learn.microsoft.com/en-us/cpp/standard-library/vector-class?view=msvc-170
  11. Standard-library algorithms

    Microsoft · docs

    Find algorithm contracts rather than memorizing every overload.

    https://learn.microsoft.com/en-us/cpp/standard-library/algorithm?view=msvc-170
  12. Lambda expressions

    Microsoft · docs

    Check capture syntax and callable behavior.

    https://learn.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=msvc-170
  13. C++ templates

    Microsoft · docs

    Study type-parameterized functions and classes beyond the small examples.

    https://learn.microsoft.com/en-us/cpp/cpp/templates-cpp?view=msvc-170
  14. C++ exception handling

    Microsoft · docs

    Understand failure propagation and implementation guidance for MSVC.

    https://learn.microsoft.com/en-us/cpp/cpp/exception-handling-in-visual-cpp?view=msvc-170
  15. std::unique_ptr reference

    Microsoft · docs

    Verify exclusive ownership, transfer, and destruction behavior.

    https://learn.microsoft.com/en-us/cpp/standard-library/unique-ptr-class?view=msvc-170
  16. Object lifetime and RAII

    Microsoft · docs

    Connect object lifetime to resource release without writing manual cleanup paths.

    https://learn.microsoft.com/en-us/cpp/cpp/object-lifetime-and-resource-management-modern-cpp?view=msvc-170
  17. Thread safety in the C++ standard library

    Microsoft · docs

    Check which sharing guarantees a library object actually provides.

    https://learn.microsoft.com/en-us/cpp/standard-library/thread-safety-in-the-cpp-standard-library?view=msvc-170
  18. Copy constructors and copy assignment

    Microsoft · docs

    Verify member-wise copying and the responsibility to define meaningful copying for resource-owning types.

    https://learn.microsoft.com/en-us/cpp/cpp/copy-constructors-and-copy-assignment-operators-cpp?view=msvc-170
  19. A Tour of C++: author information and samples

    Bjarne Stroustrup · book

    Use the author’s authorized information and samples; the full commercial book is not redistributed here.

    https://www.stroustrup.com/Tour.html
  20. CppCon 2022: C++ Value Semantics

    CppCon / Klaus Iglberger · Watch / course

    Watch the official conference recording after the copy, move, and ownership chapters.

    https://www.youtube.com/watch?v=G9MxNwUoSt0

Continue on OpenLearning

Use the subject library to move between reading, practice, study material, and the wider topic map.

Make the explanation better

If a paragraph needs a clearer example, a command changes, or a diagram hides an important assumption, propose a correction in the open-source repository. Explain the issue and add a source or a reproducible example.

Editable book sources on GitHub

Original OpenLearning instructional text and diagrams: CC BY-SA 4.0. Original code: MIT. External material retains its own copyright and license. This book links to authorized resources; it does not relicense them.