Skip to content

Latest commit

 

History

History
1588 lines (1126 loc) · 86 KB

glossary.md

File metadata and controls

1588 lines (1126 loc) · 86 KB

© A.Voß, FH Aachen, codebasedlearning.dev

Glossary and Background

Shared definitions for the course snippets.

In Markdown files the headings are the blocks, and every entry below carries an explicit anchor — <a id="raii"></a> — which is what a reference resolves against.

From a snippet, an entry is addressed by that id:

[#raii]      a link; the link text is the entry's headline
![#raii]     an embed, folded until the reader clicks the triangle
!![#raii]    an embed, pinned open
[RAII](docs/glossary.md#raii)     the explicit, path-carrying form

The baseline is C++23 (see CMAKE_CXX_STANDARD in the top-level CMakeLists.txt).

Building and running

Translation unit

One source file after preprocessing — the unit the compiler actually sees, and the unit the linker later joins with the others. Headers are not compiled on their own; they become part of every translation unit that includes them.

static at file scope gives a name internal linkage, meaning it is invisible to every other translation unit; an unnamed namespace does the same and is preferred in modern C++, because it also works for types.

#include

A preprocessor directive: it pastes the content of a file into the current one, as if it had been written there.

Angle brackets (#include <iostream>) search the compiler's include paths, quotes (#include "utils.hpp") search the directory of the including file first. The preprocessor performs a literal text substitution — which is why a header must protect itself against being included twice, see also include guard.

Include guard

Protection against a header being pasted into the same translation unit twice, which would redefine every class in it. Either the portable macro form or #pragma once, which every compiler this course targets supports:

#pragma once            // ... or:
#ifndef CBL_PRINTING_HPP
#define CBL_PRINTING_HPP
...
#endif

using

Three distinct meanings share the keyword: a using-declaration pulls one name into scope (using std::cout;), a using-directive pulls in a whole namespace (using namespace std; — avoid it outside a small scope, and never use it in a header, where it is forced on every file that includes it), and a type alias names a type (using catalog_t = std::unordered_map<std::string, book>;), which replaces C's typedef and is the only form that works with templates.

/*

  • Use of multiple declarators in a single using declaration is possible since C++17.
  •  using std::cout, std::endl;
    
  • A global 'using' directive for the std namespace is also possible. While convenient, it should
  • be avoided as it pollutes the global namespace and increases the chance of name collisions.
  •  using namespace std;
    

*/

#pragma

An instruction to the compiler outside the language itself; a compiler skips the pragmas it does not know, usually with a warning. Two kinds appear in this course: #pragma once, see include guard, and - for didactic purposes only - #pragma GCC diagnostic, e.g.

#pragma GCC diagnostic ignored "-Wuninitialized"    // gcc and clang

which switches off the warning about reading an uninitialized variable, so that we can do exactly that and watch what happens; with push and pop around it, only for the lines in between. Never do this in production code. See also Preprocessor.

Preprocessor

The text-substitution pass that runs before compilation proper: it resolves #include, expands macros, and evaluates #if. It knows nothing about types, scopes or C++ syntax, which is why modern C++ replaces macros with constexpr constants, inline functions and templates wherever it can.

Compiler, linker, main

The compiler turns each translation unit into an object file; the linker joins the object files and the libraries into one executable and resolves every name that was only declared. A program has exactly one main, which returns int — return EXIT_SUCCESS; (from <cstdlib>) says "nothing went wrong" more legibly than return 0;, and falling off the end of main means the same thing.

The build process: compile each file alone, link all together, run

main

The main function is the program's entry point, and its return value is the program's exit status. 0 (or EXIT_SUCCESS) means success, anything else an error. The shell can evaluate it, e.g. in make && ./a.out, which runs the program only if make succeeded.

Declaration vs. definition

A declaration introduces a name and its type; a definition also provides the body or the storage. A name may be declared many times and defined once, see ODR.

double pot(double b, int n);        // declaration - enough to call it
double pot(double b, int n) { … }   // definition
int v1;                             // declaration AND definition (in a function: uninitialized!)

One Definition Rule (ODR)

Every function or variable used in a program must have exactly one definition across all translation units; classes and templates may be defined in several, provided the definitions are token-for-token identical — which is what makes header-only code legal. inline marks a definition as "may appear in several translation units, they are all the same one", which is why header-only helpers and inline variables (C++17) exist.

Undefined behavior (UB)

Code for which the standard imposes no requirement at all: reading an uninitialized variable, indexing past the end of an array, dereferencing a dangling pointer, signed overflow. The program may crash, may print garbage, or may appear to work — and the compiler is allowed to optimize on the assumption that UB never happens, which is why "it worked on my machine" is not evidence of anything.

int v1;                     // no initializer at block scope
std::cout << v1;            // UB - not "some random number", UB

UndefinedBehaviorSanitizer (-fsanitize=undefined, gcc and clang, not MSVC) adds a check to signed arithmetic, divisions, shifts and more, and reports every failed check at runtime with file, line and values. It does not see uninitialized reads, and a sanitized build no longer lets the optimizer exploit the UB - it finds the problem, it does not show what the Release build will do.

Build system: make and CMake

make rebuilds only what changed, driven by rules in a makefile. CMake generates those build files from a portable CMakeLists.txt — which is where this course sets CMAKE_CXX_STANDARD 23 and where the cbl_utils target makes <cbl/printing.hpp> findable from every unit.

Header and source file

A class usually lives in two files: the header (sensor.hpp) with the class definition — data members and declarations of the member functions — and the source file (sensor.cpp) with the definitions of the member functions, each prefixed with the class name (double sensor::value() const { … }). Every file that uses the class includes the header; only the source file is compiled for the definitions, and the linker connects the calls to them. The data members must be in the header, private or not: every translation unit that creates an object needs its sizeof.

add_executable(program main.cpp sensor.cpp)    # all .cpp files, not the header

Linker errors

Errors that appear after every file has compiled, when the linker joins the object files:

  • undefined reference (gcc), Undefined symbols (Apple clang) — a function was declared and called, but no object file contains its definition: a .cpp file is missing from the build, a definition was forgotten, or its signature does not match the declaration.
  • multiple definition (gcc), duplicate symbol (Apple clang) — two object files contain the same function, usually because a header with a function body is included in several .cpp files. Fix: move the body into a .cpp file, or mark it inline, see ODR.

The message names the function — mangled or demangled — and the object file that needs or defines it.

Symbols and name mangling

An object file has a symbol table: the names of the functions and variables it defines, and of those it needs from elsewhere. nm lists it, one line per symbol, with a letter:

  • T — defined here, in the code; other object files may use it.
  • U — undefined: used here, defined elsewhere; the linker must find exactly one T for it.
  • t — defined here, but local — e.g. in an unnamed namespace; invisible to the linker.
  • W — a weak definition: template instances and inline functions, generated in every translation unit that uses them. The linker keeps one and drops the others, see ODR. macOS nm shows them as T; nm -m says weak external.

The names are mangled: the name, its namespace or class, and the parameter types are encoded into one identifier — area(double) becomes _Z4aread, area(double, double) _Z4areadd (with one more _ in front on macOS). That is how overloads get different symbols; the return type is not part of it (except for template instances), which is why functions cannot be overloaded on the return type alone. nm -C and c++filt demangle the names. MSVC mangles differently (?area@@YANN@Z); its tool is dumpbin /symbols.

Static and dynamic library

A static library is an archive of object files (libname.a; MSVC: name.lib), built with ar or CMake's add_library(name STATIC ...) and used with target_link_libraries. The linker copies into the program only the members that define a symbol still undefined — an unused object file stays out — and the GNU linker reads its inputs from left to right, so a library comes after the files that need it. A dynamic library (.so, .dylib, .dll; add_library(name SHARED ...)) stays a file of its own and is loaded when the program starts.

A variable shared between files is declared extern in the header (extern int count; — a declaration, no memory) and defined in exactly one .cpp file (int count{0};). Since C++17, an inline variable may instead be defined in the header; as for inline functions, the linker keeps one copy (see ODR).

extern "C"

Gives a function C linkage: its symbol is the plain name, without mangling — extern "C" int count(const char*) is count for the linker (_count on macOS), not _Z5countPKc. That is how C code can call a C++ function, and how C++ calls C libraries: their headers declare the functions in an extern "C" { ... } block, which is why nm shows U strlen. Without mangling there is no overloading — two extern "C" functions cannot share a name. The calling convention does not change.


Types, values, initialization

Uniform initialization

Brace initialization, T x{…}, usable everywhere: for primitives, aggregates, classes and containers. Preferred in this course because it is the one syntax that works for every type and rejects narrowing instead of warning about it.

int    v3{42};          // value 42
int    v4{};            // value-initialized: 0, not garbage
double d{1.0};
std::vector<int> primes{2, 3, 5, 7, 11};

The one trap: for std::vector, braces prefer the initializer-list constructor — std::vector<int> a(5) is five zeros, std::vector<int> a{5} is one element with value 5.

Narrowing conversion

A conversion that may lose information: double to int, a wide integer to a narrower one, or any value the target type cannot represent. Uniform initialization makes it an error, = initialization at most a warning (e.g. with -Wconversion). One exception in practice: an int variable in braces for a double - double d{n}; - is only a warning with gcc, an error with clang. What happens to the bits: integer conversions.

int a = 1.2;                    // compiles, a == 1
int b{1.2};                     // error: narrowing conversion
int c = 123456789012345;        // compiles, the value is cut off
int d{123456789012345};         // error

Integer conversions

What happens to the bits when an integer changes its type - in two's complement, which C++20 guarantees:

  • wider, from a signed type: the sign bit is copied into the new bits, a sign extension - -5 stays -5 (movsx, sxtw);
  • wider, from an unsigned type: the new bits are 0;
  • the same size, signed to unsigned or back: the bits stay, only their meaning changes - -1 becomes 4294967295, and no instruction is needed;
  • narrower: the lower bits stay - 300 as a std::uint8_t is 44.

In an expression with two types, the usual arithmetic conversions choose one first; types smaller than int become int, and between int and unsigned the choice is unsigned: -1 < 1u is false. std::cmp_less and its siblings (C++20) compare by value. A double to an int is not a matter of bits: it is converted, truncated toward zero, and a value out of range is UB.

Default values

A local variable of a built-in type has no default value: int v; inside a function holds whatever was in that memory before, and reading it is UB. Empty braces ask for one: int v{}; is value-initialized - 0 for numbers, false for bool, nullptr for pointers. Variables with static storage (globals, static locals) are zero-initialized anyway, and class types run their default constructor - a std::string starts empty.

const

A promise to the compiler and to the reader that a value will not change through this name. Applies to variables, parameters, return types and member functions:

const double pi{3.14159};
void print(const std::string& s);          // no copy, no modification
[[nodiscard]] double celsius() const;      // member function: does not modify *this

const is checked at compile time and costs nothing at runtime — see const correctness for why it is the default here.

constexpr

May be evaluated at compile time. On a variable it means "constant, known at compile time"; on a function it means "usable in a constant expression, if the arguments are". Replaces macros for constants.

constexpr double zero_celsius_in_kelvin{273.15};
constexpr int square(int n) { return n * n; }
constexpr int nine = square(3);   // computed by the compiler
int m = square(runtime_value);    // same function, computed at runtime
  • Use constexpr when the value is conceptually a compile-time constant.
  • Use const when a value should not change after initialization but may only be known at runtime.

consteval and constinit

C++20. consteval makes compile-time evaluation mandatory — an "immediate function" that cannot be called at runtime at all. constinit says a variable with static storage must be initialized at compile time (no static initialization order surprises), without making it const.

consteval int cube(int n) { return n * n * n; }
constexpr int c = cube(3);        // fine
// int r = cube(read_number());   // error: not a constant expression
  • const: A value cannot be modified after initialization.
  • constexpr: A variable must have a compile-time constant initializer. A constexpr function can be evaluated at compile time.
  • consteval: A function must be evaluated at compile time when called in a context requiring immediate evaluation.

auto

Type deduction from the initializer. The type is still static and fixed — the compiler writes it out, not the programmer. Useful where the type is long, obvious, or unspeakable (lambdas, iterators).

auto i{42};                       // int
auto& r = v[0];                   // reference - without & you get a copy
for (const auto& x : container)   // the workhorse form

auto drops references and top-level const unless you write them back, which is the single most common source of accidental copies.

decltype and trailing return type

decltype(expr) is the declared type of an expression, without evaluating it. A trailing return type moves the return type behind the parameters, where it can name them:

template <class A, class B>
auto add(A a, B b) -> decltype(a + b) { return a + b; }

Since C++14 a plain auto return type deduces the same thing in most cases; the trailing form still matters when the type depends on the parameters.

Primitive types and fixed-width integers

bool, char, int, double and friends are built in; their sizes are implementation-defined, only their minimum ranges are guaranteed. Where the width matters, use <cstdint>: std::int8_t, std::uint32_t, std::int64_t.

The classic trap: std::int8_t is signed char on every common platform, so streams print it as a character, not as a number — +x (or, later, static_cast<int>(x)) prints the number.

C++ does not promise IEEE 754 for floating point, but double is IEEE 754 binary64 on every platform this course targets.

Bit operations and masks

&, |, ^ and ~ combine or flip all bits at once, << and >> move them — each a single instruction. With a mask, x |= m sets bits, x &= ~m clears them, x ^= m toggles them and (x & m) != 0 tests them; a field is taken out with a shift and a mask, (x >> 16) & 0xff. Two traps: operands smaller than int are promoted to int first (~uint8_t{1} is a negative int), and a shift by the width of the type or more is undefined. std::byte is a byte with only these operators; <bit> (C++20) has popcount, countr_zero, has_single_bit, rotl and more.

Byte order

The order in which the bytes of a number lie in memory. Little-endian — the lowest byte first — is used by x86-64 and ARM64 in all common systems; big-endian is the order of network protocols and some file formats. std::endian::native (C++20) tells which one a program runs on, std::byteswap (C++23) reverses the bytes of an integer. It matters as soon as bytes leave the program: in a binary file, or on the network.

Floating point (IEEE 754)

A float has 1 sign bit, 8 bits of exponent (stored with a bias of 127) and 23 bits of mantissa, the digits after an implicit leading 1; a double has 1, 11 and 52. Most decimal fractions, 0.1 among them, have no finite binary form and are rounded — so 0.1 + 0.2 != 0.3, and floating-point numbers are compared with a tolerance. Infinity and NaN are special bit patterns (all exponent bits set); NaN is not equal to anything, itself included. std::bit_cast shows the bits.

sizeof, size_t, ptrdiff_t

sizeof(T) is the size of a type in bytes, evaluated at compile time. std::size_t is the unsigned type it yields and the type every container's .size() returns; std::ptrdiff_t is the signed type a pointer subtraction yields. Mixing size_t with int in comparisons is a warning worth listening to: unsigned arithmetic wraps rather than going negative.

The standard only guarantees an order, 1 == sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long). long has 8 bytes on Linux and macOS, but 4 on Windows (LP64 vs. LLP64) - use long long or std::int64_t when you need 64 bits. Whether a plain char is signed or unsigned is implementation-defined as well: signed on x86 and on Apple silicon, unsigned on ARM Linux.

std::string

An owning, growing sequence of characters with RAII semantics: it allocates, copies and frees for you. + concatenates, .size(), .substr(), .find() do the obvious, and .starts_with() (C++20) / .contains() (C++23) save a comparison against npos.

Small string optimization (SSO)

A std::string object has room for a few characters of its own. A short text is stored right there, inside the object - on the stack, if the string is a local - and no heap allocation happens. Only a longer text goes to the heap, and the object keeps its address. The limit depends on the library: 15 characters with libstdc++ (gcc) and MSVC, 22 with libc++ (Apple clang). sizeof(std::string) and s.capacity() make it visible. The general technique is the small buffer optimization.

std::string_view

C++17. A non-owning view of a character sequence: a pointer and a length. Copying one costs nothing, so it is the right parameter type for a function that only reads a string — and the wrong type to store, because it does not keep the characters alive.

void greet(std::string_view name);                   // no copy of the caller's string
std::string_view bad = std::string{"temp"};          // dangling immediately

A view is two words — 16 bytes on a 64-bit platform, whatever the length of the text. It knows its length, the characters do not: data() of a view into the middle of a text is not '\0'-terminated, so it is not a C string.

std::span

C++20. The same idea as string_view for elements of any type: a non-owning view of contiguous memory — a pointer and a count. A span<const int> parameter accepts a std::array, a std::vector or a part of them (first, last, subspan) without copying; a span<int> may change the elements. With the count in the type, span<int, 3>, only the pointer is stored.

long long sum(std::span<const int> values);          // array, vector, or a part of them
void double_all(std::span<int> values);              // writes through the view

Type conversion: stoi, stod, to_string

std::stoi / std::stod parse a number out of a std::string and throw (std::invalid_argument, std::out_of_range) rather than returning an error code — so they belong in a try/catch. std::to_string goes the other way; std::format (C++20) does it better.

Structured bindings

C++17. Names for the members of a pair, tuple, aggregate or map element:

for (const auto& [isbn, book] : catalog)
    std::println("{}: {}", isbn, book.title);

Reads better than it->first / it->second, and auto& binds without copying.

Aggregate

A struct (or class) with no private data, no user-declared constructors (since C++20, = default counts too), no virtuals — so it can be initialized member by member with braces, including by name (designated initializers, C++20):

struct fraction { int num; int den; };
fraction f{3, 4};
fraction g{.num = 3, .den = 4};      // C++20

Scope

The region of a program in which a name is visible — a namespace, a class body, a function, a block. Nothing forces a helper into a class: a static member function's only advantage over a free function is that it lives in the scope a reader searches first, and that it may touch the class's private members.

Not to be confused with lifetime: static at block scope changes the lifetime of a variable, not the scope in which its name can be used.

Lifetime

The period during which an object exists and its address is valid: from the end of its constructor to the start of its destructor. Automatic ("stack") objects die at the closing brace, dynamic objects when deleted or when their smart pointer lets go, static objects at program end. Nearly every pointer bug in this course is a lifetime bug.

Temporary object

An object without a name, created in the middle of an expression: tower{4}, the result of a function returned by value, or the result of an implicit conversion through a non-explicit constructor. It lives until the end of the full expression — the ; — and then its destructor runs. A reference to a part of it, e.g. to a member returned by a getter, dangles after that; only binding the temporary itself to a const& extends its lifetime.

Namespace and unnamed namespace

A named scope that keeps unrelated names apart (std::, cbl::). Outside it, a name needs its prefix (geo::distance) or a using. A namespace is open: several blocks, in several headers, add to the same one — that is how std is spread over the standard headers. namespace course::geo { … } nests (C++17), and namespace fs = std::filesystem; gives a long name a short alias.

A namespace costs nothing at runtime: it is only a part of the name, also in the object file: units::to_fahrenheit(double) becomes the symbol _ZN5units13to_fahrenheitEd, a nested name like a member function (see symbols).

An unnamed namespace gives everything inside it internal linkage — visible only in this translation unit — and is the modern replacement for file-scope static, because it also works for types.

namespace geo { double distance(const point& a, const point& b); }  // in a header
namespace { void define_and_init() { … } }                          // helper, private to this file

Argument-dependent lookup (ADL)

For an unqualified call, the compiler also searches the namespaces of the argument types: length(p) with a geo::point p finds geo::length without geo::. That is how cout << p finds an operator<< declared next to its class, and cout << s finds std::operator<< for a string — in a << b, there is no place for a namespace prefix. Also called Koenig lookup.


Functions and control flow

Function overloading

Several functions may share a name if their parameter lists differ; the compiler picks by the argument types (overload resolution). The return type alone is not enough to distinguish two overloads. Default arguments (void log(std::string_view msg, int level = 0);) often replace an overload — and must be given once, in the declaration.

Parameter passing

Four choices, one decision table:

Form Copy? Caller's object changed? Use for
T v yes no small, cheap types
const T& v no no anything bigger, read
T& v no yes out-parameters
T* v no yes, and may be null optional out-parameter

Call-by-value on a struct copies every member — measurable as soon as the struct holds a std::string.

Calling convention

The rules of a platform for how a function gets its arguments and returns its result: which registers, what goes to the stack, who cleans up. Every compiler on the platform follows them, so that object files from different compilers can call each other.

Platform Integers, addresses Floating point Result Larger structs
x86-64 Linux, macOS rdi, rsi, rdx, rcx, r8, r9 xmm0-xmm7 rax, xmm0 over 16 bytes: stack
ARM64 x0-x7 d0-d7 x0, d0 over 16 bytes: an address
Windows x64 rcx, rdx, r8, r9 xmm0-xmm3 rax, xmm0 over 8 bytes: an address

A large result is built at an address the caller passes as a hidden argument (rdi, x8, rcx) — the mechanism behind copy elision. Small, trivially copyable structs travel in registers, which is why they are passed by value; a type with a copy constructor of its own, like std::string, is always passed via an address. On ARM64, a struct of up to four doubles travels in d registers.

Range-based for

Iterates anything with begin()/end() — arrays, containers, ranges:

for (const auto& x : v) …    // read
for (auto& x : v) x *= 2;    // modify in place
for (auto x : v) …           // copy per element - deliberate, or an accident?

switch and fallthrough

Selects on an integral or enum value. Without break, control falls through to the next label — legal, occasionally intended, and worth marking as such with [[fallthrough]]; (C++17) so the reader and the compiler both know it was on purpose. A default: label makes the intent explicit even when it does nothing.

Branch prediction

A processor starts instructions long before the ones in front of them are finished. At a branch - an if, a loop, a switch, an indirect jump such as a virtual call - it cannot wait for the condition or the address: it guesses, from the history of that branch, and goes on. A right guess costs almost nothing; a wrong one throws away the work started on the wrong path. So a branch that goes the same way many times in a row is cheap, and one that goes either way at random is expensive - sorting the data by the condition can make the same loop much faster.

nodiscard

C++17 attribute [[nodiscard]]: warns when the return value is thrown away. Belongs on functions whose result is the point — a computed value, an error code, a handle, a RAII wrapper. C++20 allows a reason: [[nodiscard("check the error code")]].

noexcept

A promise that a function throws nothing. Not merely documentation: containers use it to decide whether they may move elements while reallocating, so move constructors and swaps should be noexcept. If a noexcept function does throw, std::terminate is called — whether the stack is unwound first is up to the implementation, and there is no second chance.

Recursion

A function calling itself, with a base case that ends it. Each call gets its own frame on the stack — deep recursion runs out of it, and C++ makes no guarantee of tail-call elimination.


References, pointers, memory

Reference

An alias for an existing object: same object, second name. Must be initialized, can never be rebound, and cannot be null.

int  a{1};
int& r{a};      // r IS a
r = 2;          // a == 2

const T& binds to temporaries as well and extends their lifetime to the reference's — the reason it is the default parameter type for anything larger than a pointer.

Pointer

A variable holding an address. Must be dereferenced (*p) to reach the object, can be null, can be re-pointed, and can be compared and printed. Where a reference says "this object", a pointer says "possibly an object, possibly none, possibly a different one tomorrow".

int  v{1};
int* p{&v};     // p holds the address of v
*p = 2;         // v == 2
p = nullptr;    // legal for a pointer, impossible for a reference

nullptr

C++11. The typed null pointer literal — NULL and 0 are integers in disguise and pick the wrong overload. Dereferencing a null pointer is UB; check before you deref, or use a reference if null is not a case you want to handle.

Pointer arithmetic and array decay

Adding to a pointer moves it in units of the pointed-to type, not bytes, so p + 1 and &a[1] are the same address. An array converts ("decays") to a pointer to its first element at the slightest provocation — which is exactly when it loses its length, and why std::array and std::vector exist.

int  a[5]{};
int* p = a;          // decay - sizeof(p) says nothing about the 5
p[3] = 1;            // same as *(p + 3)

Linked list

A chain of nodes, each with its payload and the address of the next node; nullptr in the last one ends the list. A doubly linked list stores the address of the previous node as well. Inserting or removing a node changes a few addresses — no element moves, and pointers to the other nodes stay valid. The price: no pointer arithmetic (the i-th node is i steps away), one address per node, and nodes spread over memory, each step a load that waits for the one before. The standard library has std::forward_list (singly linked) and std::list (doubly linked); in practice, std::vector wins more often than expected.

struct node {
    int payload;
    node* next;             // the address of the next node, or nullptr
};
for (const node* p{head}; p != nullptr; p = p->next) { /* ... */ }

C string

An array of char that ends with '\0', the character with the value 0 — the way C represents text. The literal "Kind" is a const char[5]. The length is stored nowhere: strlen finds it by walking to the '\0', every time. Passed on, the array decays to a const char*, and everything that takes one — cout <<, strlen, std::string{p} — reads up to the zero; without one, it reads on. == on two const char* compares addresses, strcmp compares characters. The functions of <cstring> (strcpy, strncpy, memcpy, memset) trust the caller with every size. From a std::string: c_str(), which guarantees the '\0'.

Stack and heap

Automatic variables live on the stack: allocation is a pointer bump, lifetime ends at the closing brace, size must be known at compile time. Dynamic objects live on the heap (free store): allocation is a library call, lifetime is manual (or RAII-managed), size may be computed at runtime. Prefer the stack; reach for the heap when the object must outlive the scope or is too large or too variable for it.

The stack has a fixed size, set when the thread starts: on Linux usually 8 MiB for the main thread (ulimit -s), less for other threads (512 KiB on macOS). Every call takes a frame; a recursion that is too deep, or a local array that is too large, runs past the end into a guard page the system keeps unmapped — a stack overflow, which ends the program with a segmentation fault (exit status 139 on Linux), not with an exception.

Memory layout of a program

A running program sees one address space, divided into regions: the machine code (.text), constants and string literals (.rodata), globals with a value (.data), globals that are zero (.bss — only its size is stored in the file), the heap, and the stack of each thread. The names are those of Linux (ELF); macOS and Windows use others for the same idea. Globals with a constructor are initialized before main and destroyed after it.

The addresses are virtual: the system maps them page by page (usually 4 KiB, 16 KiB on Apple silicon) to physical memory, and only when a page is first touched. malloc gets its memory from the system in large pieces — on Linux with brk for small blocks and mmap for large ones — and hands it out in small blocks.

The memory of a running program: stack, heap, globals, constants and code

new and delete

Allocate on the heap and construct; destruct and free. Every new needs exactly one delete, every new[] exactly one delete[], on every path including the one an exception takes. This is why modern C++ writes make_unique instead — new in application code is a code smell in the Core Guidelines sense.

new throws std::bad_alloc rather than returning null (unless you ask for new (std::nothrow)).

The first step can be swapped. A class can declare its own operator new and operator delete: members, implicitly static, found before the global ones. new T and delete then use them for T, and ::new T and ::delete skip past them to the global ones. The two pairs must not be mixed. Pools and arenas work this way; arrays need operator new[] and operator delete[] in addition.

Array cookie

new T[n] for a type with a destructor asks operator new[] for a few bytes more than n * sizeof(T) and stores the count n in front of the first element - the cookie; the address it returns is behind it. delete[] reads the count to call n destructors, and gives the block back from its real start. That is why delete and delete[] must match: the wrong one runs the wrong number of destructors and hands the allocator an address it never gave out. For types without a destructor - int, a plain struct - there is nothing to count and no cookie. Its size belongs to the ABI: 8 bytes on x86-64 and ARM64 Linux (checked) and on Windows; Apple's ARM64 ABI also stores the size of an element, 16 bytes (not checked here).

Placement new

new (address) T{...} constructs an object at an address you provide, without allocating - the second of the two steps of new. The object is destroyed with an explicit destructor call, p->~T(), and the memory is released separately. std::construct_at and std::destroy_at (<memory>) are the same with names. Containers work this way: a vector allocates its capacity as raw memory, and constructs and destroys its elements in it one by one.

malloc / free

The C allocator: raw bytes, no constructor, no destructor, returns null on failure. Never mix with new/delete, and never use it on a type with a constructor. Present in this course to show what new adds.

Memory leak

Allocated memory that is never freed because the last pointer to it was lost. Not a crash and not a warning — just a program that grows until it dies. The cure is ownership: exactly one owner, RAII-managed.

Dangling pointer / reference

A pointer or reference to an object whose lifetime has ended: returning the address of a local, keeping a string_view of a temporary, holding an iterator across a push_back. Reading through it is UB, and it usually "works" for a while, which is the worst possible failure mode.

this

Inside a non-static member function, a pointer to the object the function was called on — const when the function is const. this->x disambiguates a member from a parameter of the same name; *this is the object, which is what an assignment operator returns.

C++23 adds deducing this (auto&& self as an explicit first parameter), which removes a class of const/ref duplication — current compilers support it, but this course sticks to the classic form.

Address-of and std::addressof

&x yields the address of x — unless the class overloaded operator&, in which case it yields whatever that returns. std::addressof(x) gets the real address regardless, which is what generic code must use.

Const pointers vs. pointers to const

Read the declaration right to left:

const int* p;        // pointer to const int   - *p is fixed, p may move
int* const p{&i};    // const pointer to int   - p is fixed, *p may change
const int* const p{&i};   // both

const_cast removes the const — legal, and UB if you then write through it to an object that really is const.


Classes

struct vs. class

The same construct with one difference: members of a struct default to public, members of a class to private. Convention, not rule: struct for plain data (aggregates), class where there is an invariant to protect.

Access modifiers

public — everyone; protected — the class and its derived classes; private — the class and its friends. The question to ask first is who wants access: a user of an instance always needs public, a derived class may be served by protected.

Constructor

The member function that turns raw storage into an object with an invariant. If it throws, the object never existed — members constructed so far are destroyed, and no destructor runs for the object itself.

explicit Temperature(double celsius) : celsius_{celsius} {}

Member initializer list

The : member_{value}, other_{…} part between the constructor's signature and its body. Members are initialized here, in declaration order; assigning in the body instead means default-constructing first and overwriting after — impossible for const members and references, wasteful for everything else.

Destructor

Runs when the object's lifetime ends, in reverse order of construction, and releases whatever the object owns. A destructor must never throw — during stack unwinding a second exception calls std::terminate. Destructors are implicitly noexcept.

explicit

Forbids a constructor (or conversion operator) from being used for an implicit conversion. Without it, any one-argument constructor doubles as a silent conversion — void f(Temperature); f(20.0); compiles and probably should not. The rule of thumb: single-argument constructors are explicit unless the conversion is the point.

const member function

double celsius() const; — promises not to modify the observable state of the object, and is the only kind callable on a const object or through a const&. Skipping it is what forces callers to drop const, one caller at a time, until nothing is const any more.

See also mutable for the deliberate exception.

mutable

A data member that may change even in a const member function — for caches, lazily computed values, mutexes and counters, i.e. state that is not part of what the object means. (In a lambda, mutable means something related but different: the captured copies may be modified.)

Copy constructor and copy assignment

T(const T&) builds a new object from an existing one; T& operator=(const T&) overwrites an existing one. The compiler generates both member-wise, which is correct as long as every member owns itself — and wrong the moment a raw pointer is involved, see deep vs. shallow copy.

Deep vs. shallow copy

A shallow copy duplicates the pointer, so two objects believe they own the same memory — double delete, or modification through one showing up in the other. A deep copy duplicates what the pointer points to. Members that own themselves (string, vector, unique_ptr) make the question disappear, which is the Rule of Zero.

Rule of Zero / Three / Five

  • Zero: define none of the special members. Let RAII members manage resources. This is the goal.
  • Three: if you define any of destructor, copy constructor, copy assignment, you probably need all three (C++98 resource management).
  • Five: with C++11, add move constructor and move assignment to that set.
  • Move-only (rare, e.g. a file handle): delete the copy operations and provide the moves.

= default and = delete

= default asks for the compiler's version explicitly (and keeps the type trivial where possible); = delete removes a function, so using it is a compile error rather than a surprise. Deleting the copy operations is how a type says "I am not copyable".

Static member

Belongs to the class, not to an instance: one shared variable, or a function with no this. Reachable as Temperature::is_plausible(20.0), and — legally but pointlessly — through an object. static constexpr data members can be initialized in the class body; other static data members need a definition in exactly one .cpp file (or inline, C++17). A static data member is not part of the object - sizeof does not count it - but lives in static storage, next to the global variables. A class template has one per instantiation: registry<int>::count and registry<double>::count are two variables.

Three meanings of static

One keyword, three jobs:

  1. File scope: internal linkage — invisible to other translation units. Superseded by the unnamed namespace.
  2. Function-local: one instance, initialized on first use, outliving the call. Thread-safe initialization since C++11.
  3. Class member: belongs to the type, see static member.

What a function-local static costs: with a constant initializer, nothing more than a global variable - it is ready before main. With an initializer that must run, a guard variable is tested at every call, and the first call goes through __cxa_guard_acquire and __cxa_guard_release, so that two threads cannot both initialize it. An object with a destructor is destroyed after main returns. constinit (C++20) demands the constant initialization. Across translation units, the order in which globals are initialized is not defined - a function-local static is the usual way out.

Named constructor

A static member function that returns an object, used where a constructor would be ambiguous or unnamed:

static Temperature from_kelvin(double kelvin);   // reads better than Temperature(double, tag)

C++ constructors cannot be named or overloaded on intent, only on parameter types — so the idiom trades Temperature{300.0, kelvin_tag{}} for a name a reader understands. It is the closest counterpart to Python's @classmethod alternative constructor, minus the cls parameter.

friend

Grants one function or class access to the private members of another. Used sparingly and deliberately — most often for operator<<, which cannot be a member because its left operand is the stream. A friend is part of the class's interface, not a hole in it.

Operator overloading

Giving operators a meaning for your own type. Choose member vs. free function by the left operand: a + b where a is yours can be either, std::cout << a must be free (usually a friend). Keep the conventional semantics — + should not print, [] should not allocate — and provide += first, then define + in terms of it.

number& operator=(const number& rhs);          // member
int3 operator+(int3 a, int3 b) noexcept;       // free, symmetric
double operator()(double x) const;             // call operator: polynomial(x)
T& operator[](std::size_t i);                  // index operator
std::ostream& operator<<(std::ostream&, const T&);

C++20's operator<=> generates the six comparisons from one definition, see three-way comparison.

For the compiler, an operator is a call: a + b is operator+(a, b), a += b is a.operator+=(b) - C++ Insights shows it. Precedence, associativity and the number of operands stay those of the built-in operator. In the object file, an operator has a mangled name like every function (_Zpl... for +, pL for +=, ls for <<), and as Release a small one is inlined - a + b for a class holding a long long is the same instruction as for two long longs. An overloaded &&, || or , loses the short-circuit.

Three-way comparison <=>

a <=> b (C++20, the "spaceship") says whether a is less than, equal to or greater than b: a std::strong_ordering, or a std::partial_ordering for floating-point, where a NaN is unordered. With = default, the compiler compares member by member, in the order of declaration. It also rewrites the other comparisons: a < b becomes (a <=> b) < 0, and a != b becomes !(a == b) - two defaulted operators give all six.

struct version {
    int major;
    int minor;
    bool operator==(const version&) const = default;
    auto operator<=>(const version&) const = default;   // 1.2 < 1.10
};

Short-circuit evaluation

The built-in && and || evaluate the right operand only if the left one does not decide the result: p != nullptr && *p > 0 never dereferences a null pointer. An overloaded && or || is a function call, and all arguments of a call are evaluated before it - the short-circuit is gone. That is why they are not overloaded. Since C++17, the left operand is at least evaluated first.

Conversion operator

operator double() const; — lets an object convert to another type. Same warning as the explicit constructor: without explicit, the conversion happens silently in overload resolution, which can make two unrelated types compare equal by accident.

Getter and setter

Accessors that keep a member private while exposing its value. Worth it when they enforce an invariant, validate, or notify; pure pass-throughs are just a longer public:. C++ has no properties — a wrapper class can approximate the syntax, at a cost.

RAII

Resource Acquisition Is Initialization: a resource — memory, file, lock, socket — is owned by an object, acquired in its constructor and released in its destructor. Since destructors run on every exit path, including the one an exception takes, cleanup cannot be forgotten.

{
    std::ofstream f{"log.txt"};      // acquire
    f << "hello";
}                                    // released here, exception or not

The whole standard library is built this way: string, vector, unique_ptr, lock_guard.


Inheritance and polymorphism

Inheritance

class button : public widget — a button is a widget and contains one as a sub-object. Constructors run base-first, destructors derived-first. The access specifier on the base (public, protected, private) limits how visible the inherited members are to users of the derived class; public is the only one that models "is a".

SOLID

Five principles for the design of classes, collected by Robert C. Martin (SOLID):

  • Single responsibility: a class has one reason to change — no "god object" that parses, computes and prints.
  • Open-closed: open for extension, closed for modification — a new kind of shape is a new derived class, not a new case in every switch.
  • Liskov substitution: a derived class keeps every promise of its base — a square that derives from a resizable rectangle breaks it.
  • Interface segregation: several small interfaces (abstract classes with pure virtual functions) rather than one large one that forces classes to implement what they do not need.
  • Dependency inversion: high-level code depends on an interface, not on a concrete class; the concrete one is passed in, e.g. as a std::unique_ptr<interface> or a reference.

Four of the five are about interfaces and inheritance, so in C++ they mean virtual functions — and their price, one pointer per object and an indirect call.

virtual and dynamic dispatch

A virtual function is chosen by the dynamic type of the object, through a pointer or reference, not by the static type of the expression. Without virtual, C++ calls what the pointer's type says — unlike Java, where every method is virtual by default.

widget* w = new button{};
w->draw();          // button::draw() only if draw is virtual

In the machine, a virtual call is two loads and an indirect jump: the vptr from the object, the address of the function from the table, then a jump to it (mov rax, [rdi], jmp [rax+16] on x86-64). A non-virtual call has the address of the function in the instruction. The jump is cheap when it is predicted and expensive when the types are mixed at random; it also keeps the compiler from inlining - unless it devirtualizes the call.

override and final

C++11. override says "this replaces a base virtual" and turns a typo — a wrong signature, a missing const — into a compile error instead of a second, never-called function. final forbids further overriding (or, on a class, further derivation).

vtable

The usual implementation of dynamic dispatch: each polymorphic class has a table of function pointers, and each object of it carries a hidden pointer to that table. Hence the cost — one pointer per object, one indirection per call — and hence zero overhead: you pay it only for classes that declare a virtual function.

With gcc and clang (the Itanium C++ ABI), the vptr is the first 8 bytes of the object, and it points 16 bytes into the table: in front of that address are the offset to the top of the object and a pointer to the type information; from there on, the addresses of the virtual functions in the order of declaration - a virtual destructor takes two slots, one that destroys and one that destroys and frees (delete). The table is in static storage, one per class; nm -C lists it as vtable for circle. The constructors write the vptr - the base first, so during the base's constructor the object is a base - and the destructors write it back. The table is emitted in the object file that defines the key function, the first virtual function that is neither pure nor defined in the class; without that definition, the linker reports an undefined reference to 'vtable for circle'. A class with two polymorphic bases has two vptrs; a virtual base is found through an offset in the table.

Abstract class and pure virtual function

virtual void draw() = 0; makes the class abstract: it cannot be instantiated, only derived from. A class of nothing but pure virtuals is C++'s interface. A pure virtual destructor is legal and still needs a definition, because the derived destructor calls it.

Virtual destructor

delete base_ptr; where the object is really a derived one is UB unless the base destructor is virtual. Rule: a base class intended for polymorphic deletion declares a virtual destructor — or a protected non-virtual one, if deletion through the base is not allowed.

Object slicing

Copying a derived object into a base-typed variable keeps only the base part; the derived state and the vtable pointer are lost, so virtual calls resolve to the base. Passing by value is the usual accident — void f(widget w) instead of void f(const widget& w).

The vptr is not copied at all: the copy constructor of the base writes the vptr of the base, as every constructor of the base does. So the copy is a complete base object - never half a derived one. To copy a polymorphic object, a virtual clone asks the object to copy itself.

Multiple inheritance and the diamond

A class may have several bases. If two of them share a base, that base exists twice — the diamond problem — and member access becomes ambiguous. class b : virtual public a makes the shared base a single sub-object, at the cost of a more complex layout and construction order (the most-derived class initializes the virtual base).

In memory, the bases are sub-objects one after the other. Only the first one starts at the address of the object: a pointer to the second base is the address plus an offset - the conversion adds it and keeps a null pointer null - and a virtual call through the second base goes through a thunk that subtracts it again (non-virtual thunk to ... in nm). The offset of a virtual base depends on the complete object, so it is stored in the vtable: every access is one load more, and a class with a virtual base has a vptr even without virtual functions. Multiple inheritance of interfaces - classes with only pure virtual functions - is the common case, and costs one vptr per interface.

Devirtualization

A virtual call made as a direct call, because the compiler knows the dynamic type: the object is a local, its class is final, or the call names the class (c.circle::area(), never virtual). Then the call can be inlined, too. gcc also devirtualizes speculatively: it compares the slot in the table with the address of the function it expects, and runs the inlined code if they are equal.

RTTI: typeid and dynamic_cast

Run-time type information: for every polymorphic class, the compiler emits a std::type_info object - nm lists it as typeinfo for circle - and the vtable points to it. typeid(expr) on a reference to a polymorphic class reads it through the vptr - the dynamic type; for any other type, it is the static type, known at compile time. name() is implementation-defined (gcc and clang: the mangled name).

dynamic_cast<circle*>(p) checks at run time: a call into the runtime library (__dynamic_cast), which walks the classes described by the type information and returns nullptr if the object is no circle; for a reference, it throws std::bad_cast. It needs a polymorphic class. static_cast down a hierarchy does not check - one instruction, or none - and a wrong one is UB. A chain of dynamic_casts usually stands for a missing virtual function.

Empty base optimization

An object takes at least one byte, so that two objects have two addresses - but an empty base class may take no space at all: it shares the address of the derived object. struct counter : empty { int count; } is 4 bytes, with an empty member it is 8. The standard library uses it - or [[no_unique_address]] - to store empty helpers such as the deleter of a unique_ptr for free.

Casts

Four named casts, each with a job, all greppable — unlike the C-style (T)x, which silently picks whichever of them fits:

  • static_cast<T> — well-defined conversions: numeric, up/down a hierarchy without a check, void* back to T*.
  • dynamic_cast<T*> — checked downcast in a polymorphic hierarchy; yields nullptr (pointers) or throws std::bad_cast (references).
  • const_cast<T> — adds or removes const. Writing through a removed const on a truly const object is UB.
  • reinterpret_cast<T> — reinterprets the bits. Portable only in the narrow cases the standard lists.
  • std::bit_cast<T> (C++20, <bit>) — the bits of a value, as a value of another type of the same size.

In the machine, a cast is an instruction or nothing. A conversion between number types may compute a new value (cvttsd2si for double to int, movsx for a wider signed type) or keep the bits (int to unsigned). reinterpret_cast and const_cast only change the type the compiler sees - no instruction, and no check. A user-defined conversion - a conversion operator or a converting constructor - is a call. C++ Insights shows which named cast a C-style cast stands for.

Strict aliasing

An object may be read and written only through its own type - or a signed or unsigned variant of it, or char, unsigned char and std::byte. The compiler relies on that: a float* and a std::uint32_t* are assumed never to point to the same object, so a value may stay in a register across a write through the other pointer. Reading a float as *reinterpret_cast<std::uint32_t*>(&f) is therefore UB, even where it seems to work. For the bits of a value: std::bit_cast or std::memcpy.

enum and enum class

A plain enum leaks its enumerators into the surrounding scope and converts to int on sight. A scoped enum (enum class color { red, green };, C++11) does neither: names are color::red, and conversion needs an explicit static_cast. The underlying type can be fixed (enum class flags : std::uint8_t).

In memory, an enum is its underlying type: int for an enum class without :, a type the compiler chooses for a plain enum, or the one after the : - sizeof shows it. With a fixed underlying type, every value of that type is a valid value of the enum, named or not: static_cast<suit>(7) is fine. So a switch over an enum must be ready for values without a name - and gcc and clang turn a switch that maps every name to a value into a table, with a range check in front. std::to_underlying (C++23) gives the number in the underlying type.


Templates and generics

Function and class template

A pattern the compiler instantiates per type used. Templates live in headers, because the definition must be visible where it is instantiated (ODR permits it).

template <class T> void join(const T& container);
template <class T, std::size_t N> class my_array { … };

Template parameters and instantiation

Parameters may be types (class T / typename T — same thing), non-type values (std::size_t N), or templates. Instantiation is the compiler generating one concrete class or function per distinct argument list — which is why templates cost compile time and code size but no runtime dispatch, see zero overhead.

Specialization

Providing a different implementation for particular arguments: full specialization fixes every parameter, partial specialization fixes some (only for class templates; functions overload instead).

template <class A, class B> struct my_pair { … };      // primary
template <class A> struct my_pair<A, bool> { … };      // partial
template <> struct my_pair<int, int> { … };            // full

Type traits

Compile-time queries and transformations over types, in <type_traits>: std::is_integral_v<T>, std::remove_reference_t<T>, std::decay_t<T>. The classic use is a specialization selected by a trait; since C++17 if constexpr often replaces that with a plain branch that is compiled away.

Concepts and requires

C++20. Named constraints on template parameters, checked at the call site — so the error says "not sortable" instead of forty lines from inside the algorithm.

template <class T>
concept numeric = std::is_arithmetic_v<T>;

template <numeric T> T twice(T v) { return v + v; }

Standard library

Sequence containers

Container Storage Good at
std::array fixed, inline size known at compile time
std::vector contiguous, heap the default; index and iterate
std::deque chunked push/pop at both ends
std::list doubly linked splice, stable addresses

vector grows geometrically: capacity() may exceed size(), and a reallocation invalidates every iterator and pointer into it.

Associative containers

std::set / std::map keep keys sorted in a balanced tree — O(log n), ordered iteration, needs <. std::unordered_set / std::unordered_map hash them — O(1) on average, no order, needs == and a hash. Reach for the unordered ones unless the order matters.

std::pair and std::tuple

Heterogeneous fixed-size bundles: .first/.second for a pair, std::get<0>() for a tuple, or structured bindings for both. Fine as a return type for two values that have no name worth inventing — a named struct beats them the moment they have one.

Iterator

A generalized pointer: *it reads, ++it advances, it != end tests. Every container provides begin()/end(), cbegin()/cend() for const access, and rbegin()/rend() for reverse traversal. Half-open ranges throughout: end() points past the last element.

Algorithms

<algorithm> operates on iterator ranges rather than containers: std::sort, std::find_if, std::for_each, std::accumulate (in <numeric>), std::transform. Prefer them to hand-written loops — they say what, not how, and they are hard to get wrong.

Ranges and views

C++20. The same algorithms taking a container directly (std::ranges::sort(v)) plus lazy, composable views:

for (int x : v | std::views::filter(even) | std::views::take(3)) …

A view owns nothing and computes on demand — cheap to copy, and dangling if the underlying range dies first.

std::optional, variant, expected

C++17 brought std::optional<T> ("a T or nothing", better than a magic value) and std::variant<A, B> (a type-safe union). C++23 adds std::expected<T, E> ("a T or an error"), the return-value counterpart to exceptions. Compiler support for expected is recent — check your toolchain before relying on it.

Streams

std::cout, std::cin, std::cerr for the console; std::ifstream / std::ofstream for files (RAII: they close themselves); std::istringstream / std::ostringstream for parsing and building strings in memory. std::endl flushes — '\n' usually suffices and is faster.

std::format, std::print, std::println

std::format("{:.2f}", x) (C++20) builds a string from a pattern; std::print and std::println (C++23, header <print>) write one directly, without the << chain. Type-safe, and the format string is checked at compile time.

std::println("{}| {} = {:.3f}", i, name, value);

Needs a recent libstdc++/libc++ — where it is missing, std::format plus std::cout is the fallback.


Errors and exceptions

Exception

An error signalled by throw and handled by the nearest matching catch, unwinding the stack — and running every destructor on the way — in between.

try {
    auto n = std::stoi(text);
} catch (const std::invalid_argument& e) {   // specific first
    std::println("not a number: {}", e.what());
} catch (...) {                              // catch-all last
    throw;                                   // rethrow, keep the type
}

Catch by const& (copying slices, see slicing), order handlers from specific to general, and let the exception carry the message — e.what().

Stack unwinding

What happens between throw and catch: the runtime leaves every function on the way without finishing it, removes its stack frame, and destroys every local object in it — in reverse order of construction, exactly as at a normal }. This is what makes RAII work with exceptions. If a destructor throws during unwinding, there would be two exceptions at once; the program ends with std::terminate. If no catch matches at all, it is implementation-defined whether the stack is unwound before std::terminate is called.

Standard exception types

All derive from std::exception: std::logic_error (invalid_argument, out_of_range, domain_error) for bugs the caller could have prevented, std::runtime_error (range_error, system_error) for conditions only discovered while running, plus std::bad_alloc and std::bad_cast. Derive your own from std::runtime_error rather than from std::exception directly — you get the what() machinery for free. Catch by const&: a catch by value copies the exception into the handler's type and slices it, and what() returns the base's text.

Exception safety

What a function guarantees when it throws: basic (nothing leaks, invariants hold), strong (the operation either completes or changes nothing — see copy-and-swap), or nothrow (noexcept). RAII is what makes the basic guarantee automatic rather than a matter of discipline.

assert and static_assert

assert(cond) checks a precondition at runtime and aborts if it fails (disabled by NDEBUG in release builds) — for bugs, not for user input. static_assert(cond, "message") checks at compile time and belongs in templates, where it turns an invalid instantiation into a readable error.


Move semantics and value categories

lvalue and rvalue

An lvalue has a name and an address you can take (v, v[0], *p); an rvalue is a temporary about to expire (42, f(), std::move(x)). T& binds to lvalues, const T& to both, and T&& binds only to rvalues — which is what lets a function know its argument is disposable.

Move semantics

C++11. Transferring the guts of an expiring object instead of copying them: the move constructor T(T&&) noexcept and move assignment T& operator=(T&&) noexcept take the resource and leave the source in a valid but unspecified state (typically null/empty).

smart_ptr(smart_ptr&& other) noexcept : p_{other.p_} { other.p_ = nullptr; }

Cheap for anything that owns a heap allocation — string, vector, unique_ptr — and identical to a copy for a plain int.

std::move

Moves nothing: it is a cast to an rvalue reference, saying "I am done with this, take it if you can". After moving from an object, only assign to it or destroy it. Do not std::move a return value of a local — it blocks copy elision.

Copy elision, RVO

The compiler constructing the result directly in the caller's storage, so neither a copy nor a move happens. Since C++17 this is guaranteed when a function returns a prvalue (return Temperature{20.0};) and optional but routine for a named local (NRVO). Which is why "return by value is slow" has been folklore for a decade.

Copy-and-swap

An assignment operator written as: take the parameter by value (the copy or move happens there, and may be elided), then swap with *this. Self-assignment works, the strong exception guarantee follows from the copy happening before any state changes, and copy and move assignment collapse into one function.

smart_ptr& operator=(smart_ptr other) noexcept { swap(*this, other); return *this; }

Smart pointers and ownership

Ownership

The answer to "who calls delete, and when". A raw pointer says nothing about it, which is why modern C++ encodes it in the type: unique_ptr (exactly one owner), shared_ptr (several), weak_ptr (none, observes), plain T* or T& (a non-owning reference, valid only as long as the owner says).

std::unique_ptr

The default smart pointer: sole ownership, zero overhead over a raw pointer, non-copyable and movable, deletes on destruction. Create it with std::make_unique<T>(args…), hand it around with std::move, pass the object (const T&) to functions that only use it.

auto w = std::make_unique<widget>(42);
use(*w);                       // borrow
auto w2 = std::move(w);        // transfer; w is now null

std::shared_ptr and weak_ptr

shared_ptr counts owners in a control block and deletes when the count hits zero — pay for it only when ownership really is shared. Two objects pointing at each other keep the count above zero forever: a cycle, i.e. a leak. weak_ptr observes without owning and must be lock()ed into a shared_ptr before use, which is how the observer pattern and parent-pointers in trees are built.

Prefer std::make_shared<T>(…): one allocation for object and control block.

Small Buffer Optimization (SBO)

Storing small payloads inline in the object and only allocating on the heap when they outgrow it — what most std::string implementations do for short strings. Trades object size for allocations, and forces the class to implement the Rule of Five by hand, since the inline buffer cannot simply be pointer-swapped.


Functional C++

Lambda expression

An anonymous function object written where it is used:

auto add = [](int a, int b) { return a + b; };
std::ranges::sort(v, [](const auto& a, const auto& b) { return a.size() < b.size(); });

[](){} in full: capture, parameters, body. Generic lambdas take auto parameters (C++14); mutable allows modifying captured copies.

Underneath, a lambda is an object of a class the compiler writes for it - the closure type: every capture is a data member, the body is a const operator(). So sizeof of a lambda is the size of its captures (a lambda without captures takes 1 byte, as every empty object), and C++ Insights shows the class. Every lambda expression has a type of its own, which a template can be instantiated with - the reason why std::sort with a lambda can inline the comparison. Only a lambda without captures converts to a function pointer.

Lambda capture

What the lambda takes from the enclosing scope: [x] by copy, [&x] by reference, [=] / [&] everything (avoid: it hides which), [this] the enclosing object, [x = std::move(y)] an init-capture (C++14). A by-reference capture that outlives its scope is a dangling reference — the standard bug in a lambda handed to a thread.

Function pointer and std::function

A function pointer (double (*f)(double)) holds the address of a function - 8 bytes, and a call through it is an indirect call, unless the compiler knows the value and inlines. std::function<double(double)> is a type-erased wrapper that stores any callable — function, lambda, functor — at the price of its size (32 bytes with libstdc++, 48 with libc++), an allocation for a callable that does not fit into its small buffer, and an indirect call that is rarely inlined. An empty std::function throws std::bad_function_call when called. Use a template parameter where the type can be deduced, std::function where it must be stored.

C++23 adds std::move_only_function for callables that cannot be copied.


Concurrency

std::thread

Starts a function on a new thread of execution; must be join()ed or detach()ed before it is destroyed, or the program calls std::terminate. Arguments are copied — wrap in std::ref to pass a reference.

std::thread t{[&]{ work(); }};
t.join();

C++20's std::jthread joins in its own destructor (RAII) and supports cooperative cancellation — prefer it where available.

Race condition

A data race: two threads touching the same data, at least one writing, without synchronization. The result depends on timing, and the standard calls it UB rather than "sometimes wrong". (A race condition in the wider sense is any timing-dependent bug; the data race is the one that is UB.) Not fixable by reordering statements or adding sleeps — only by a mutex, an atomic, or not sharing.

std::mutex

Mutual exclusion: one thread at a time inside the critical section. lock()/unlock() by hand works until an exception or an early return skips the unlock — which is why the manual form appears once in this course and never again.

lock_guard, unique_lock, scoped_lock

RAII wrappers for a mutex: std::lock_guard locks on construction and unlocks on destruction, full stop. std::unique_lock can also unlock and relock, which condition variables require. std::scoped_lock (C++17) takes several mutexes at once, deadlock-free — the sane default for multiple locks.

Condition variable

Lets a thread wait until another signals that something changed, without busy-waiting. Always used with a unique_lock and a predicate, because waits may wake up for no reason (spurious wakeup):

cv.wait(lock, []{ return done; });      // re-checks the predicate on every wake

The waiting side must hold the lock while testing the condition; the notifying side sets it under the lock and then calls notify_one/notify_all.

thread_local

A variable with one instance per thread - created when the thread starts (or at its first use), destroyed when the thread ends. The machine finds the current thread's instance through a register that the operating system sets at every switch: fs on x86-64 (add DWORD PTR fs:x@tpoff, 1), tpidr_el0 on ARM64. For data that each thread needs for itself - a counter, a buffer, a random generator - without any synchronization.

std::atomic

std::atomic<T> makes every operation on a T one indivisible step for all threads: ++a, a += n, a.load(), a.store(v), a.exchange(v), a.compare_exchange_strong(expected, v). For an int or a pointer, it is the T itself - sizeof(atomic<int>) is 4 - and the operations are single instructions: lock add or lock xadd on x86-64, ldadd or a ldaxr/stlxr loop on ARM64. For large types, is_always_lock_free is false, and the library uses a lock. Each operation is atomic, not a sequence of them: if (a == 0) { a = 1; } is two steps - use compare_exchange_strong.

std::atomic<int> counter{0};
++counter;                                  // from any thread

Memory order

Processors and compilers reorder loads and stores as long as the thread itself cannot tell. An atomic operation says how much order it needs: std::memory_order_relaxed - only the operation itself is atomic; release (for a store) and acquire (for a load) - what was written before the release is visible after an acquire that sees it; seq_cst, the default - one order of all atomic operations for all threads. x86-64 needs extra work only for seq_cst stores (xchg); ARM64 needs ldar/stlr for acquire and release. Use the default unless you have measured and understood.

Cache line and false sharing

Caches copy memory in lines of 64 bytes (on current x86-64 and ARM64 processors). A core that writes to a line must own it exclusively; another core that writes to the same line takes it over. Two threads that write to different variables in the same line pass the line back and forth - false sharing: correct, and several times slower. Keep variables that different threads write often at least 64 bytes apart - alignas(64), or std::hardware_destructive_interference_size where the library defines it - or keep them in locals and write once.

std::async, std::future, std::promise

std::async(std::launch::async, f, args...) runs f in another thread and returns a std::future - a handle for the result; get() waits for it, and throws what f threw. A std::promise is the other end: a thread sets the value or the exception, another waits at the future. Between them is a shared state on the heap. The future of std::async waits in its destructor - a future that is thrown away makes the call synchronous.

std::future<long long> result{std::async(std::launch::async, sum_up_to, 1000)};
// ... other work ...
std::cout << result.get();

Deadlock

Two threads each holding what the other needs, both waiting forever. Avoid by locking in a fixed global order, holding one lock at a time, or taking them together with std::scoped_lock.


Principles and style

Zero overhead

C++'s central bargain: you do not pay for what you do not use, and what you do use you could not have hand-coded better. No garbage collector, no universal base class, no vtable unless a class declares a virtual function, no exception cost on the path that does not throw. The corollary is the unforgiving half — no bounds checks either, unless you ask for .at().

Const correctness

Marking everything that does not modify observable state as const — parameters, locals, member functions — so the compiler enforces intent and the reader knows what a call can do. It also composes: a const object is only usable through const member functions, so a single missing const propagates outward until someone reaches for const_cast.

Const-correctness is a core building block of C++ design: express intent by defaulting to const and relaxing only when mutation is required.

const ≠ immutable:

  • const applies to the object you see, not necessarily the whole reachable state. It is a compile-time qualifier preventing certain writes through a particular handle.
  • Immutability means the entire logical state of the object never changes after construction. It is a stronger design property about an object's whole (logical) state over time.

Value semantics

Objects behave like values: copying makes an independent object, assignment overwrites, equality compares contents. Java-style reference semantics happen in C++ only where you ask for them (pointers, references, shared_ptr). Most bugs from other languages arrive here — the copy that was expected to be an alias, or the alias expected to be a copy.

Code Style

The points that matter most in this course:

  • four spaces, no tabs; braces on the same line as the statement
  • lower_snake_case for functions and variables, _ suffix for data members
  • [[nodiscard]] on functions whose result is the whole point
  • const by default — on member functions, parameters and locals
  • prefer uniform initialization (double x{1.0}) over = where it reads clearly
  • one demo function per topic, called from main

The Modern Way

Solving a problem the way the standard library and the Core Guidelines suggest rather than the way C would: values and references over raw pointers, RAII over manual cleanup, range-based for over index arithmetic, constexpr over macros, unnamed namespaces over file-scope static. Shortest definition: code that makes an experienced C++ reader nod instead of reach for a debugger.