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
Clear explanations. Worked examples. Practice with reasoning. Original text · CC BY-SA 4.0 Code · MIT
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
Basic terminal navigation and file editing
A compiler with C++17 support
Willingness to predict and test small examples
What you will be able to do
Build a C++17 executable and diagnose build stages
Choose clear value, borrowing, and ownership interfaces
Use standard containers and algorithms with valid lifetimes
Design class invariants and report input errors honestly
Build and test a complete study-log summary
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
Executable examples target C++17. C++20 concepts, ranges, coroutines, modules, advanced metaprogramming, ABI design, and lock-free algorithms need further study.
Examples are original teaching material. External sources retain their own licenses and are linked rather than copied.
Compiler flags shown use GCC/Clang syntax on a Unix-like shell. Adapt commands for your platform.
No guide can substitute for compiling, tracing, and modifying the examples. Runtime checks and boundaries are deliberately part of the learning path.
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 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.
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.
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';
}
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.
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';
}
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.
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 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.
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.
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.
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.
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.
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';
}
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.
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.
start outer
start inner
end inner
between
end outer
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.
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.
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
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.
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.
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
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 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.
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';
}
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
Given durations 25, 10, 40, and 15, ascending sorting produces 10, 15, 25, 40.
The captured threshold is 20, so exactly 25 and 40 satisfy the predicate.
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.
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';
}
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 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.
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';
}
}
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.
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.
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 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.
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 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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.