C++ Handbook
C++ is a general-purpose language for native applications and libraries. It supports procedural, object-oriented, and generic programming. Classes, templates, and RAII let programs express invariants, reusable operations, and resource ownership. C++ shares much syntax with C, and each language has its own type and conversion rules.
Pick C++ when
- You need C-level performance with high-level abstractions — zero-cost abstractions (templates, inline, constexpr) mean you pay only for what you use. Game engines, physics simulators, and trading systems live here.
- You are building a real-time system with predictable latency — no GC pauses, manual memory control, and RAII give you deterministic resource management.
- You need to interoperate with a C codebase and add OOP on top — keep a C-compatible interface when linking C and C++ components. Compile each source file in its own language mode.
- Template metaprogramming or generic libraries are the goal — the STL, Eigen, Boost, and CUDA all rely on C++ templates for compile-time generics with zero runtime cost.
- Embedded targets with some resources — you get C-level control but can use classes and RAII. Microcontrollers with a few KB of RAM still support a useful subset of C++.
Think twice before choosing C++ when
- Team size and onboarding matter — C++ is one of the hardest languages to learn and review. Undefined behavior, ODR violations, and template error messages are notoriously opaque.
- You need memory safety guarantees — C++ has smart pointers but no borrow checker. Rust offers comparable performance with provable safety. For new projects where safety is non-negotiable, Rust is the better bet.
- Build times are a constraint — large C++ projects can take minutes to compile. C++ modules (C++20) help, but the ecosystem is still catching up.
- You just need a fast scripting layer — Python with C extensions, or Go, will be far easier to maintain for network tools and data pipelines that don't need microsecond latency.
C++ vs. its closest alternatives
- C++ vs C — C++ gives you RAII, OOP, templates, and exceptions at zero added runtime cost. Unless you need a tiny binary or strict POSIX C compliance, prefer C++.
- C++ vs Rust — both give native performance. Rust prevents memory bugs at compile time; C++ gives you more flexibility (and more rope to hang yourself). New projects prioritising safety should lean Rust; large existing C++ codebases stay C++.
- C++ vs Java/C# — Java and C# are far easier to write safely and have huge ecosystems. Choose them for enterprise applications; choose C++ when GC pauses or binary portability matter.
Your First Program
Check your GCC or Clang installation with c++ --version. Save the program as main.cpp. Substitute g++ or clang++ if that is your compiler command.
The iostream header declares the standard output stream. Each insertion sends text or a newline to that stream.
#include <iostream>
int main() {
std::cout << "Hello!" << '\n';
}Run the commands from the directory containing main.cpp. In Windows PowerShell, name the executable hello.exe and run .\hello.exe. The output is Hello!
c++ -std=c++17 -Wall -Wextra main.cpp -o hello
./helloResources
- Compiler installation on Windows
- cppreference.com — C++ — the most complete C++ language and library reference
- isocpp.org — ISO C++ committee and community hub
- C++ Core Guidelines — Stroustrup & Sutter's authoritative style guidance
- Compiler Explorer — inspect assembly output across compilers and standards
- CppCon — annual conference talks (many free on YouTube)
Topics
For standalone lessons, save the code as main.cpp and reuse the first build command. Use -std=c++20 or -std=c++23 where indicated and a standard library that supports the feature. Blocks with statements outside main are fragments. Place those statements inside main and keep includes and function definitions outside it.
Variables & Types
Types determine valid operations and representations. Initialize at declaration and use const for values that should remain unchanged.
Auto deduces a type from the initializer. A plain auto declaration usually drops references and top-level const. Use auto with an ampersand when the binding should refer to the original object.
Choose a type from the initializer
The literal 3 gives count type int. Use 3.0 when fractional arithmetic is intended.
auto count = 3;Print fundamental values
#include <iostream>
#include <string>
int main() {
// Fundamental types
int i = 42;
long l = 1234567890L;
long long ll = 9999999999LL;
float f = 3.14f;
double d = 3.14159265;
char c = 'A';
bool b = true;
// auto — type deduced by compiler
auto x = 42; // int
auto y = 3.14; // double
auto z = 'A'; // char
// const and constexpr
const int MAX = 100;
constexpr double PI = 3.14159265;
// Uniform initialization (C++11)
int arr[]{1, 2, 3};
std::string str{'h', 'e', 'l', 'l', 'o'};
std::cout << i << ' ' << d << '\n';
return 0;
}This program prints 42 and the double rounded to the stream’s default precision.
Check a deduced type at compile time
#include <type_traits>
int main() {
auto rate = 0.5f;
static_assert(std::is_same_v<decltype(rate), float>);
}The f suffix makes rate a float. The static assertion verifies the type without running any code.
Initialization Forms
Initialization forms have different overload and conversion rules. Braces reject narrowing conversions but can prefer initializer-list constructors.
Brace initialization rejects narrowing conversions. For a type with an initializer-list constructor, braces can select a different overload from parentheses, so compare what each form constructs.
Compare braces and parentheses
A vector built with (3, 7) contains three copies of 7. A vector built with {3, 7} contains the two values 3 and 7. Predict the size before running the example.
The brace example prints 3 and 2.
Value-initialize a scalar
Empty braces initialize count to zero. This is useful for counters that begin before any input arrives.
int count{};#include <iostream>
#include <vector>
int main() {
std::vector<int> repeated(3, 7);
std::vector<int> listed{3, 7};
std::cout << repeated.size() << ' ' << listed.size() << '\n';
}Further examples
Compare initialization forms
// C-style initialization
int a = 5;
double pi = 3.14;
// Copy initialization
std::vector<int> v1{1, 2, 3};
std::vector<int> v2 = v1; // copy
// Direct initialization
std::vector<int> v3(5, 0); // 5 zeros
std::string s1(3, 'x'); // 'xxx'
// Uniform / brace initialization (C++11)
int c{42};
int d{}; // zero-initialize
std::vector<int> v4{1, 2, 3, 4};
std::pair<int, int> p{1, 2};Copy, direct and brace syntax select how a value is initialized.
Initialize aggregates and detect narrowing
// Use the relevant declarations and includes from the preceding fragment.
// Aggregate initialization
struct Point { int x; int y; };
Point pt{10, 20}; // members in declaration order
// Narrowing prevention — brace init rejects truncation
// int bad{3.14}; // error: narrowing conversion
int good = static_cast<int>(3.14); // explicit cast required
// Designated initializers (C++20)
struct Config {
int width = 800;
int height = 600;
bool fullscreen = false;
};
Config cfg{ .width = 1920, .height = 1080 }; // C++20
// unmentioned members keep their defaultsBraces reject narrowing. C++20 designators name aggregate members in declaration order.
References
References alias existing objects. Ensure the referred object outlives every use, especially when returning references from functions.
A reference aliases an existing object. A const reference permits reading through it. The object must remain alive for as long as the reference is used.
Predict which value changes
The program prints 7 and then 9. Changing the copy leaves the original at 7. Assigning through the reference changes the original to 9.
Borrow read-only access
Reading view now gives 9 because it aliases score. Const restricts access through the reference.
int score = 7;
const int& view = score;
score = 9;#include <iostream>
int main() {
int original = 7;
auto copy = original;
auto& alias = original;
copy = 9;
std::cout << original << '\n';
alias = copy;
std::cout << original << '\n';
}Further examples
Bind references and pass arguments
int x = 10;
int& ref = x; // lvalue reference — alias for x
ref = 20; // modifies x through the alias
const int& cref = x; // const ref (read-only, no copy)
// Rvalue reference (C++11)
std::string s{'h', 'e', 'l', 'l', 'o'};
std::string&& rref = std::move(s); // s moved-from // C++11
// Pass by reference — avoids copy, allows mutation
void increment(int& val) { val++; }
increment(x); // x becomes 21
// Pass by const reference — avoids copy, read-only
void print(const std::string& str) {
std::cout << str << '\n';
}A mutable reference aliases the caller’s object. A const reference lets the function read it without copying.
Return and forward references
#include <utility>
// Returning a reference (ensure lifetime is valid)
int& get_elem(std::vector<int>& v, int i) { return v[i]; }
// Forwarding reference / universal reference (C++11)
template<typename T>
void forward_ex(T&& arg) { // T&& is a forwarding reference
consume(std::forward<T>(arg)); // preserves value category
}The returned reference needs a live referent. Forwarding preserves the argument’s value category.
Control Flow
Branches select execution paths and loops repeat work. Range-based loops suit traversal when the index itself is not needed.
A range-based loop visits each element. Binding by value copies the element. Binding by reference allows access to the original element.
Update elements in a range loop
The reference binds to each array element in turn. The array becomes 3, 5.
int scores[]{2, 4};
for (int& score : scores) ++score;Branch and iterate
// if with initializer (C++17)
if (int result = compute(); result > 0) {
std::cout << "positive: " << result << '\n';
} // C++17
// Range-based for loop (C++11)
std::vector<int> nums{1, 2, 3, 4, 5};
for (const auto& n : nums) {
std::cout << n << ' ';
}
// Standard loops
for (int i = 0; i < 5; ++i) { /* ... */ }
int n = 5;
while (n-- > 0) { /* ... */ }
do { /* ... */ } while (false);An initializer limits the declared name to the if statement. A range-for visits each element in order.
Select cases with switch
// switch with initializer (C++17)
switch (int code = get_code(); code) {
case 200: std::cout << "OK\n"; break;
case 404: std::cout << "Not found\n"; break;
default: std::cout << "Other\n"; break;
}
// Scoped enum
enum class Direction { North, South, East, West };
Direction dir = Direction::North;
switch (dir) {
case Direction::North: std::cout << "N\n"; break;
case Direction::South: std::cout << "S\n"; break;
default: break;
}A switch initializer is scoped to the statement. Scoped enumerators use the enum name as a qualifier.
Functions
Signatures communicate value and reference semantics. Pass small values directly and use const references for larger inputs that need no copy or modification.
Choose parameter types to show what a function needs. Values give the function its own object, references access an existing one, and const references provide read-only access through that parameter.
Choose a mutable parameter
Call increment with an int variable initialized to 4. Its value becomes 5 because the parameter aliases the argument.
void increment(int& value) { ++value; }Declare parameters and results
// Basic function
int add(int a, int b) { return a + b; }
// Default arguments
void log(const std::string& msg, int level = 1) {
std::cout << '[' << level << "] " << msg << '\n';
}
// Trailing return type
auto multiply(int a, int b) -> int { return a * b; }
// Inline — allows identical definitions in multiple translation units
inline int square(int x) { return x * x; }
// constexpr — evaluated at compile time (C++11)
constexpr int factorial(int n) { // C++11
return n <= 1 ? 1 : n * factorial(n - 1);
}
constexpr int f6 = factorial(6); // computed at compile timeDefaults fill omitted arguments. A constexpr call can be evaluated at compile time when the inputs permit it.
Overload, store and return values
// Use the relevant declarations and includes from the preceding fragment.
// Function overloading
double area(double r); // circle
double area(double w, double h); // rectangle
// std::function — type-erased callable
std::function<int(int, int)> op = add;
op(3, 4); // 7
// Structured return (C++17)
auto divide(int a, int b) -> std::pair<int, int> {
return {a / b, a % b};
}
auto [quot, rem] = divide(17, 5); // C++17Overload resolution picks a signature. std::function stores a callable and a structured binding can unpack a returned aggregate.
Containers
Choose containers by access patterns and iterator invalidation rules. Vectors provide contiguous sequences; associative containers organize lookup by keys.
Choose a container by the operations callers need. A vector stores elements contiguously, while ordered and unordered maps offer different lookup and traversal guarantees.
These examples are fragments. Keep the headers at the top of the file and place the statements inside main. The views at the end borrow storage from an existing object.
std::vector
Choose vector for a growing sequence with fast indexing. This example ends with 1, 2, 3, 4, 5. Reserve changes capacity without adding elements. Growth that reallocates invalidates references and iterators.
#include <vector>
std::vector<int> values{1, 2, 3};
values.reserve(20);
values.push_back(4);
values.emplace_back(5);std::array
Use array when the number of elements is fixed and part of the type. Here fill resets all three channels. The storage belongs to the array object, wherever that object lives.
#include <array>
std::array<int, 3> channels{255, 128, 0};
channels.fill(0);std::deque
Use deque for frequent additions and removals at both ends. The front item is removed first here, leaving 2, 3, 4. Indexing is available, but storage need not be contiguous.
#include <deque>
std::deque<int> work{2, 3};
work.push_front(1);
work.push_back(4);
work.pop_front();std::list
Use list when you already hold positions and need to insert or erase without invalidating iterators to other elements. The insertion gives 1, 2, 3, 5. Finding a position still takes a linear walk.
#include <list>
#include <iterator>
std::list<int> stops{1, 3, 5};
auto next_stop = std::next(stops.begin());
stops.insert(next_stop, 2);
stops.sort();std::forward_list
Use forward_list when traversal only needs to go forward and you can work with the predecessor of an insertion point. Inserting before the first element uses before_begin. Sorting then gives 1, 2, 3, 4.
#include <forward_list>
std::forward_list<int> pending{3, 1, 4};
pending.insert_after(pending.before_begin(), 2);
pending.sort();std::map
Use map for key-value lookup with sorted traversal. Alice prints before Bob even though Bob was inserted first. Lookup takes logarithmic time. Use find to look up a key without inserting it.
#include <map>
#include <iostream>
#include <string>
std::map<std::string, int> scores;
scores["Bob"] = 87;
scores.emplace("Alice", 95);
for (const auto& entry : scores) {
std::cout << entry.first << ": " << entry.second << '\n';
}std::unordered_map
Use unordered_map for key-value lookup when order is irrelevant. Indexing a missing key creates a zero-initialized count here, so apple ends at 2. Lookup is constant time on average and linear in the worst case.
#include <unordered_map>
#include <string>
std::unordered_map<std::string, int> counts;
++counts["apple"];
++counts["pear"];
++counts["apple"];std::multimap
Use multimap when several records can share an ordered key. The range returned for hour 9 contains both bookings.
#include <map>
#include <string>
std::multimap<int, std::string> bookings;
bookings.emplace(9, "Alice");
bookings.emplace(9, "Bob");
auto matches = bookings.equal_range(9);std::set
Use set for unique values that you also need to traverse in order. The stored values are 1 and 3, and the membership test succeeds. In C++20, contains expresses the same test directly.
#include <set>
std::set<int> rooms{3, 1, 3};
bool has_room = rooms.find(3) != rooms.end();std::unordered_set
Use unordered_set for membership or deduplication without an ordering requirement. The first insertion succeeds and the second reports that 42 was already present.
#include <unordered_set>
std::unordered_set<int> seen;
bool first = seen.insert(42).second;
bool second = seen.insert(42).second;std::multiset
Use multiset when duplicate values must be retained in sorted order. The count of 5 is 2 and traversal gives 3, 5, 5.
#include <set>
std::multiset<int> ratings{5, 3, 5};
auto fives = ratings.count(5);std::priority_queue
Use priority_queue when you repeatedly need the highest-priority item. With the default comparison, top gives 4, then 3 after pop. Check empty before calling top or pop.
#include <queue>
std::priority_queue<int> jobs;
jobs.push(3);
jobs.push(1);
jobs.push(4);
int first = jobs.top();
jobs.pop();std::bitset
Use bitset for a fixed number of binary flags. Bit 0 is the rightmost bit. Setting it and flipping bit 3 gives 10111011, with six bits set.
#include <bitset>
std::bitset<8> flags{0b10110010};
flags.set(0);
flags.flip(3);
auto enabled = flags.count();std::string_view
Use string_view to read a slice of text without copying its characters. The slice reads ell. The literal in this example stays alive throughout the program. A view of a string must stay within the lifetime of its storage.
#include <string_view>
std::string_view text = "hello";
auto middle = text.substr(1, 3);std::span
Use span in C++20 to borrow contiguous elements with their count. The assignment changes the vector to 9, 2, 3, 4. Keep the backing storage alive and rebuild the view if the vector reallocates.
#include <span>
#include <vector>
std::vector<int> values{1, 2, 3, 4};
std::span<int> view{values};
auto first_three = view.first(3);
first_three[0] = 9;Structured Bindings (C++17)
Structured bindings name components of tuple-like values and aggregates. Choose value or reference binding deliberately to control copying and modification.
A structured binding names the parts of a tuple-like object or aggregate. Binding with a reference qualifier lets the names refer to the original parts.
Decompose an array
The binding names elements of a hidden copy. The original first element stays 10.
int values[]{10, 20};
auto [first, second] = values;
first = 99;Modify a member through a binding
The reference binding names the original members. Reading point.y now gives 7.
struct Point { int x; int y; };
Point point{1, 2};
auto& [x, y] = point;
y = 7;Read keys and values from a map
The loop prints 2:4 and 3:9 in key order. The const reference avoids copying entries.
#include <map>
#include <iostream>
std::map<int, int> squares{{2, 4}, {3, 9}};
for (const auto& [key, value] : squares) std::cout << key << ':' << value << ' ';Decompose arrays and records
#include <map>
#include <tuple> // C++17 throughout
// Array decomposition
int arr[]{10, 20, 30};
auto [a, b, c] = arr; // C++17
// std::pair
auto p = std::make_pair(42, 3.14);
auto [key, val] = p;
// std::tuple
auto t = std::make_tuple(1, 2.5, 'x');
auto [i, d, ch] = t;
// Struct — public non-static data members
struct Point3D { int x; int y; int z; };
Point3D pt{1, 2, 3};
auto [x, y, z] = pt;A binding names each position or member of the source object.
Bind by reference in a loop
// Use the relevant declarations and includes from the preceding fragment.
// Range-for over std::map (most common use)
std::map<int, int> squares{{1,1},{2,4},{3,9}};
for (const auto& [k, v] : squares)
std::cout << k << ':' << v << '\n';
// Mutable bindings — modify in-place
for (auto& [k, v] : squares) v *= 2;
// const auto& — read-only access to first element
const auto& [fk, fv] = *squares.begin();
// Ignore a member with structured binding
auto [first, second] = std::make_pair(1, 2);
// use only 'first', ignore 'second' (or use [[maybe_unused]])
// [[nodiscard]] with structured return (C++17)
[[nodiscard]] std::pair<bool, int> try_parse(int raw);
auto [ok, result] = try_parse(42);
if (ok) std::cout << result;Reference bindings let iteration inspect or update the original elements, according to their const qualification.
Lambdas
Lambdas are callable objects with captured state. Value captures store copies; reference captures require the original objects to remain alive.
A value capture stores a copy in the closure. A reference capture sees later changes to the original and requires that the original outlive calls through the closure.
Capture a snapshot
The result is 13. The closure kept the value that offset had when the lambda was created.
int offset = 10;
auto add = [offset](int n) { return n + offset; };
offset = 20;
int result = add(3);Capture a live reference
Count becomes 2. Keep count alive until the final call through the closure.
int count = 0;
auto increment = [&count] { ++count; };
increment();
increment();Accept different argument types
Each call deduces its parameter type. The results are the integer 6 and the double 2.5.
auto twice = [](auto value) { return value + value; };
auto whole = twice(3);
auto fraction = twice(1.25);Choose what a lambda captures
#include <functional>
// Basic lambda (C++11)
auto square = [](int x) { return x * x; }; // C++11
// Capture by value [=] — copies all used locals
int offset = 10;
auto add_offset = [=](int x) { return x + offset; }; // C++11
// Capture by reference [&]
int count = 0;
auto inc = [&]() { ++count; }; // C++11
// Capture specific variables
auto mixed = [offset, &count](int x) { count++; return x + offset; };Value captures store copies. Reference captures observe the original objects and depend on their lifetime.
Parameterize and store a lambda
// Use the relevant declarations and includes from the preceding fragment.
// Generic lambda (C++14)
auto println = [](auto x) { std::cout << x << '\n'; }; // C++14
// constexpr lambda (C++17)
auto sq_cx = [](int x) constexpr { return x * x; }; // C++17
constexpr int sq9 = sq_cx(9); // evaluated at compile time
// Template lambda (C++20)
auto same_type = []<typename T>(T a, T b) { return a + b; }; // C++20
// Capture this
struct Counter {
int value = 0;
auto make_inc() {
return [this]() { ++value; }; // captures this pointer
}
};
// Immediately invoked lambda
int result = [](int a, int b) { return a + b; }(3, 4); // 7
// Storing in std::function (type erasure)
std::function<int(int)> fn = [offset](int x) { return x + offset; };A generic lambda deduces parameter types at each call. std::function stores a compatible callable behind a fixed signature.
Iterators
Iterators connect containers to generic algorithms. Mutation can invalidate positions, so check the container's rules before retaining an iterator across changes.
The end iterator marks an exclusive boundary and cannot be dereferenced. Container mutations can invalidate iterators, so check the rule for the operation before reusing one.
Trace a search that finds nothing
Search for a value that is absent and compare the result with end before reading it. A vector can also invalidate saved iterators when an insertion reallocates its storage. Find the position again after the mutation.
Walk a half-open range
The loop reads 2 and 4. Stop at end before dereferencing because that position marks the boundary.
#include <vector>
#include <iostream>
std::vector<int> values{2, 4};
for (auto it = values.begin(); it != values.end(); ++it) std::cout << *it << ' ';Append through an output iterator
Each assignment through the adaptor appends an element. Output becomes 0, 2, 4.
#include <algorithm>
#include <iterator>
#include <vector>
std::vector<int> input{2, 4};
std::vector<int> output{0};
std::copy(input.begin(), input.end(), std::back_inserter(output));Read a single-pass input range
The stream supplies 1, 2, and 3. Advancing consumes input, so make a vector when you need to traverse it again.
#include <iterator>
#include <sstream>
#include <vector>
std::istringstream input{"1 2 3"};
std::istream_iterator<int> first{input}, last;
std::vector<int> parsed(first, last);Navigate iterator ranges
#include <iterator>
#include <sstream>
// Iterator categories:
// input < forward < bidirectional < random-access < contiguous
std::vector<int> v{1, 2, 3, 4, 5};
// begin / end
auto it = v.begin(); // points to first element
auto end = v.end(); // one past last (sentinel)
std::cout << *it << '\n'; // 1
// Reverse iterators
for (auto rit = v.rbegin(); rit != v.rend(); ++rit)
std::cout << *rit << ' '; // 5 4 3 2 1
// Navigation helpers
auto it2 = std::next(v.begin(), 2); // points to v[2]
auto it3 = std::prev(v.end(), 1); // points to last
std::advance(it2, 1); // advance in-place by 1
auto dist = std::distance(v.begin(), it3); // 4An end iterator marks an exclusive boundary. Navigation operations depend on the iterator category.
Adapt traversal and read from streams
// Use the relevant declarations and includes from the preceding fragment.
// Iterator adaptors
std::vector<int> out;
std::copy(v.begin(), v.end(), std::back_inserter(out)); // push_back each
// std::istream_iterator
std::istringstream iss{"1 2 3"};
std::istream_iterator<int> start(iss), finish;
std::vector<int> parsed(start, finish);
// Minimal range-for cursor; it does not model the standard forward iterator concept
struct IotaRange {
int cur, last;
IotaRange(int from, int to) : cur(from), last(to) {}
IotaRange begin() const { return *this; }
IotaRange end() const { return {last, last}; }
int operator*() const { return cur; }
IotaRange& operator++() { ++cur; return *this; }
bool operator!=(const IotaRange& o) const { return cur != o.cur; }
};
for (int n : IotaRange{1, 6}) std::cout << n << ' '; // 1 2 3 4 5An adaptor changes how traversal works. An input iterator can read successive values from a stream.
Algorithms
The standard library provides algorithms for searching, transforming, and ordering elements. Copy any example to algorithms.cpp and compile with g++ -std=c++20 algorithms.cpp -o algorithms. Run ./algorithms (or .\algorithms.exe in PowerShell). The comments show the expected results.
Search and count
Use a half-open range [begin, end). The end iterator is a marker, so check it before dereferencing a search result. find looks for a value, find_if takes a predicate, and count scans the whole range to count matches.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{5, 3, 1, 3};
auto first = std::find(v.begin(), v.end(), 3);
if (first != v.end()) std::cout << first - v.begin() << '\n'; // 1
auto large = std::find_if(v.begin(), v.end(), [](int x) { return x > 4; });
if (large != v.end()) std::cout << *large << '\n'; // 5
std::cout << std::count(v.begin(), v.end(), 3) << '\n'; // 2
std::cout << std::boolalpha
<< (std::find(v.begin(), v.end(), 9) == v.end()) << '\n'; // true
}Test a condition
A predicate answers a yes-or-no question about one element. These algorithms can stop as soon as the answer is known. On an empty range, any_of returns false, while all_of and none_of return true.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{2, 4, 5};
auto even = [](int x) { return x % 2 == 0; };
std::cout << std::boolalpha
<< std::any_of(v.begin(), v.end(), even) << '\n' // true
<< std::all_of(v.begin(), v.end(), even) << '\n' // false
<< std::none_of(v.begin(), v.end(), even) << '\n'; // false
}Transform and overwrite
transform writes one result per input element. A back inserter appends to a vector, while passing the source begin iterator overwrites each element in place. fill writes one value across a subrange. replace changes only matching values.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> source{1, 2, 3, 4}, squares;
std::transform(source.begin(), source.end(), std::back_inserter(squares),
[](int x) { return x * x; }); // squares: 1 4 9 16
std::transform(source.begin(), source.end(), source.begin(),
[](int x) { return x * 2; }); // source: 2 4 6 8
std::fill(source.begin(), source.begin() + 2, 99); // 99 99 6 8
std::replace(source.begin(), source.end(), 6, 0);
for (int x : source) std::cout << x << ' '; // 99 99 0 8
}Remove matching elements
remove_if moves the retained elements to the front in their original order and returns their new logical end. The vector still has its original size. Erase the tail to shrink it, or use std::erase_if on a vector in C++20.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3, 4, 5};
auto even = [](int x) { return x % 2 == 0; };
auto keptEnd = std::remove_if(v.begin(), v.end(), even);
std::cout << v.size() << '\n'; // 5
v.erase(keptEnd, v.end());
for (int x : v) std::cout << x << ' '; // 1 3 5
// In C++20, std::erase_if(v, even) combines both steps.
}Sort and preserve ties
sort uses ascending order by default. A comparator returns true when its first argument should precede its second. Use a strict comparison, such as > for descending scores. stable_sort preserves the input order of records with equal scores.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
struct Result { const char* name; int score; };
std::vector<Result> results{{"Ana", 80}, {"Lou", 95}, {"Sam", 80}};
std::stable_sort(results.begin(), results.end(),
[](const Result& a, const Result& b) { return a.score > b.score; });
for (const auto& r : results) std::cout << r.name << ' '; // Lou Ana Sam
}Select the smallest values
partial_sort sorts only the requested prefix and leaves the rest in unspecified order. nth_element places the value that would occupy a chosen position after a full sort. The two sides can remain unordered. These operations and sort require random-access iterators, such as those of a vector.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{9, 1, 7, 3, 5};
std::partial_sort(v.begin(), v.begin() + 2, v.end());
std::cout << v[0] << ' ' << v[1] << '\n'; // 1 3
std::nth_element(v.begin(), v.begin() + 2, v.end());
std::cout << v[2] << '\n'; // 5, the median of these five values
}Partition into two groups
partition moves matching elements before the others and returns the first iterator in the second group. Each group can be in any order. Use stable_partition when the original order within each group matters.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{5, 2, 7, 4};
auto split = std::partition(v.begin(), v.end(), [](int x) { return x % 2 == 0; });
std::cout << split - v.begin() << '\n'; // 2 even values
if (split != v.end()) std::cout << *split % 2 << '\n'; // 1, an odd value
}Search sorted data
Sort with the same comparison you use for searching. binary_search answers whether a value is present. lower_bound gives the first position whose value is at least the target in ascending order, even if the target is absent. equal_range gives the half-open span of matching values.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{9, 3, 1, 3, 7};
std::sort(v.begin(), v.end()); // 1 3 3 7 9
std::cout << std::boolalpha
<< std::binary_search(v.begin(), v.end(), 3) << '\n'; // true
auto insertion = std::lower_bound(v.begin(), v.end(), 4);
std::cout << insertion - v.begin() << '\n'; // 3, before 7
auto [first, last] = std::equal_range(v.begin(), v.end(), 3);
std::cout << last - first << '\n'; // 2 matches
}Combine sorted ranges
With both inputs sorted in the same order, merge keeps every occurrence. For each value, set_union keeps the larger of the two occurrence counts and set_intersection keeps the smaller. back_inserter appends to its destination, so use separate output vectors when comparing the results.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> a{1, 2, 2}, b{2, 3};
std::vector<int> merged, combined, common;
std::merge(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(merged));
std::set_union(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(combined));
std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(common));
for (const auto& result : {merged, combined, common}) {
for (int value : result) std::cout << value << ' ';
std::cout << '\n';
}
// 1 2 2 2 3
// 1 2 2 3
// 2
}Reduce a range to one value
accumulate from <numeric> updates an accumulator once per element, from left to right. The initial value sets its type and supplies the result for an empty range. Start a product at 1 and use 0.0 to keep fractional parts when summing doubles.
#include <algorithm>
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> factors{2, 3, 4};
std::vector<double> prices{1.25, 2.5};
std::cout << std::accumulate(factors.begin(), factors.end(), 1,
std::multiplies<int>{}) << '\n'; // 24
std::cout << std::accumulate(prices.begin(), prices.end(), 0.0) << '\n'; // 3.75
std::cout << std::accumulate(prices.begin(), prices.end(), 0) << '\n'; // 3
}Filter, rank, and summarize scores
Keep passing scores with copy_if, sort them from highest to lowest, then add the top two. This C++20 example uses a ranges overload of sort that takes the vector directly. Limit the number of scores you use to the number that passed so the summary also handles zero or one passing score.
#include <algorithm>
#include <cstddef>
#include <functional>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
int main() {
std::vector<int> scores{82, 45, 91, 75, 59}, passing;
std::copy_if(scores.begin(), scores.end(), std::back_inserter(passing),
[](int score) { return score >= 60; });
std::ranges::sort(passing, std::greater<int>{}); // 91 82 75
const auto topCount = std::min<std::size_t>(2, passing.size());
const int total = std::accumulate(passing.begin(), passing.begin() + topCount, 0);
std::cout << total << '\n'; // 173
}Ranges (C++20)
Ranges and views compose traversal and transformations. Many views are lazy and reference existing storage, which must remain alive during use.
A view can filter or transform elements as iteration requests them. Compile the standalone example in C++20 mode. If a view refers to an existing range, keep that range alive for the duration of traversal.
Separate a view from stored results
The filter and transform run as elements are requested. For input 1, 2, 3, 4, selecting even values and squaring them gives 4 and 16. Store the results in a vector when they must outlive the original range.
#include <iostream>
#include <ranges>
#include <vector>
int main() {
std::vector<int> values{1, 2, 3, 4};
auto squares = values
| std::views::filter([](int value) { return value % 2 == 0; })
| std::views::transform([](int value) { return value * value; });
for (int square : squares) std::cout << square << '\n';
}Further examples
Build a lazy view
#include <ranges> // C++20
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8};
// View adaptors — lazy, no allocation
auto evens = v | std::views::filter([](int x){ return x % 2 == 0; });
auto sq = v | std::views::transform([](int x){ return x * x; });
auto first3 = v | std::views::take(3);
auto skip2 = v | std::views::drop(2);
auto rev = v | std::views::reverse;
// Chained pipe — evaluated lazily on iteration
auto result = v
| std::views::filter([](int x){ return x % 2 == 0; })
| std::views::transform([](int x){ return x * x; })
| std::views::take(3);
for (int n : result) std::cout << n << ' '; // 4 16 36Filtering and transformation take effect when the view is traversed. The view can refer back to the original elements.
Apply range algorithms and combine views
// Use the relevant declarations and includes from the preceding fragment.
// std::ranges algorithms — accept range directly
std::ranges::sort(v);
auto it = std::ranges::find(v, 4);
std::vector<int> out;
std::ranges::copy(v, std::back_inserter(out));
// Sentinels — decoupled begin/end types
auto positive = v | std::views::take_while([](int x){ return x < 5; });
// std::views::iota — integer range
for (int n : std::views::iota(1, 6)) std::cout << n << ' '; // 1 2 3 4 5
// std::views::zip (C++23)
std::vector<int> nums{'1', '2', '3'};
std::vector<char> chars{'a', 'b', 'c'};
for (auto [n, c] : std::views::zip(nums, chars)) // C++23
std::cout << n << ':' << c << ' ';
// std::views::enumerate (C++23)
for (auto [i, val] : std::views::enumerate(v)) // C++23
std::cout << i << '=' << val << ' ';Range algorithms can accept a range directly. zip and enumerate require C++23 library support.
stringstream & string_view
std::stringstream provides in-memory text serialization and parsing using the familiar stream interface. std::string_view (C++17) is a non-owning reference to a contiguous character sequence — it accepts any string-like source with zero allocation. std::from_chars / std::to_chars are the fastest locale-independent number conversions.
A string stream stores or parses text through stream operations. A string view only refers to existing characters. Keep the source alive and avoid operations that invalidate its storage.
Detect a failed extraction
Extraction fails because the input starts with a letter. Check the stream before using the result.
#include <sstream>
std::istringstream input{"room"};
int number{};
bool ok = static_cast<bool>(input >> number);Build and parse text with streams
#include <sstream>
#include <string>
#include <string_view>
#include <charconv> // C++17 from_chars / to_chars
// --- std::ostringstream: build strings efficiently ---
std::ostringstream oss;
oss << "x=" << 42 << " y=" << 3.14;
std::string result = oss.str(); // 'x=42 y=3.14'
// --- std::istringstream: parse whitespace-separated tokens ---
std::istringstream iss("10 20 30 40");
int n;
std::vector<int> nums;
while (iss >> n) nums.push_back(n); // {10, 20, 30, 40}
// --- std::stringstream: read and write ---
std::stringstream ss;
ss << 100 << ' ' << 200;
int a, b;
ss >> a >> b; // a=100, b=200Insertion writes formatted text. Extraction reads tokens and exposes stream state if conversion fails.
Inspect views and convert numbers
// Use the relevant declarations and includes from the preceding fragment.
// --- std::string_view: non-owning, zero-copy string reference (C++17) ---
std::string_view sv = "hello world";
std::string_view sub = sv.substr(6, 5); // 'world' — no allocation
bool starts = sv.starts_with("hello"); // true (C++20)
bool ends = sv.ends_with("world"); // true (C++20)
std::size_t pos = sv.find("world"); // 6
// string_view as function parameter: accepts string, literal, span, all zero-copy
void print_sv(std::string_view sv) {
for (char c : sv) std::cout << c;
std::cout << '\n';
}
print_sv("literal");
print_sv(std::string("dynamic"));
// --- std::from_chars / std::to_chars: fastest text<->number (C++17) ---
char buf[32];
auto [ptr, ec] = std::to_chars(buf, buf + sizeof(buf), 12345);
// ec == std::errc{} on success
int val = 0;
std::string_view input = "9876";
auto [p2, ec2] = std::from_chars(input.data(), input.data() + input.size(), val);
// val == 9876, ec2 == std::errc{}
// Trim leading/trailing whitespace using string_view (zero-copy)
std::string_view trim(std::string_view sv) {
while (!sv.empty() && sv.front() == ' ') sv.remove_prefix(1);
while (!sv.empty() && sv.back() == ' ') sv.remove_suffix(1);
return sv;
}A string_view borrows its input. from_chars reports the stopping position and the conversion status.
std::regex
std::regex uses ECMAScript grammar by default and offers other grammars as options. Use raw string literals (R"(...)") to avoid double-escaping backslashes. Compile the regex once (construction is expensive) and reuse the object. For performance-critical code prefer std::string::find or SIMD-based libraries; std::regex prioritises correctness and portability.
Use regex_match for a whole-input check and regex_search for a matching substring. For example, a digit pattern can find 42 inside room 42, while a whole-input check with the same pattern rejects that string. Read captures only after a successful match.
Compare whole input with substring search
Whole is false because the room prefix does not match. Part is true because 42 matches.
#include <regex>
std::regex digits{R"([0-9]+)"};
bool whole = std::regex_match("room 42", digits);
bool part = std::regex_search("room 42", digits);Match, search and capture text
#include <regex>
#include <iostream>
#include <string>
#include <iterator>
// std::regex uses ECMAScript grammar by default
// Basic match — does the entire string match?
std::regex ipv4(R"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})");
std::string addr = "192.168.1.1";
bool ok = std::regex_match(addr, ipv4); // true
// Search — find first match anywhere in string
std::regex word_re(R"(\b\w{4}\b)");
std::string text = "the quick brown fox";
std::smatch m;
if (std::regex_search(text, m, word_re)) {
std::cout << "found: " << m[0] << '\n'; // 'this' or 'quick'
}
// Capture groups
std::regex date_re(R'((d{4})-(d{2})-(d{2}))');
std::string s = "date: 2024-07-15";
if (std::regex_search(s, m, date_re)) {
std::cout << "year=" << m[1] << '\n';
std::cout << "month=" << m[2] << '\n';
std::cout << "day=" << m[3] << '\n';
}regex_match checks the whole input, while regex_search can locate a matching substring.
Enumerate and replace matches
// Use the relevant declarations and includes from the preceding fragment.
// Iterate all matches in a string
std::string src = "foo 42 bar 99 baz 7";
std::regex num_re(R'(d+)');
std::sregex_iterator it(src.begin(), src.end(), num_re);
std::sregex_iterator end;
for (; it != end; ++it)
std::cout << (*it)[0] << ' '; // 42 99 7
// Replace matches
std::regex vowels(R"([aeiou])");
std::string result = std::regex_replace(src, vowels, '*');
// Case-insensitive flag
std::regex ci_re(R"(hello)", std::regex_constants::icase);
std::regex_search("HELLO world", m, ci_re); // matches
// Compile regex once (expensive constructor — never in a loop)
static const std::regex email_re(
R'([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,})'
);
bool valid = std::regex_match("user@example.com", email_re);Use an iterator to visit each match and reuse compiled patterns across repeated searches.
Classes & OOP
Classes combine state with operations that preserve invariants. Constructors establish valid state and destructors release resources as lifetimes end.
Constructors establish invariants and destructors release owned resources. Use a virtual destructor when deleting a derived object through a base pointer is part of the interface.
Establish state at construction
A new Counter starts at zero. After one increment its getter returns 1. Private state keeps updates behind the public operations.
class Counter {
int value_ = 0;
public:
void increment() { ++value_; }
int value() const { return value_; }
};Extend an interface with inheritance
class Animal {
std::string sound_;
protected:
std::string name_;
public:
// Constructor with member-initializer list
Animal(const std::string& name, const std::string& sound)
: name_(name), sound_(sound) {}
virtual ~Animal() = default; // virtual destructor essential for polymorphism
virtual std::string speak() const {
return name_ + " says " + sound_;
}
// Rule of Five — define all or none (C++11)
Animal(const Animal&) = default; // C++11
Animal& operator=(const Animal&) = default;
Animal(Animal&&) noexcept = default;
Animal& operator=(Animal&&) noexcept = default;
};
class Dog : public Animal {
std::string breed_;
public:
Dog(const std::string& name, const std::string& breed)
: Animal(name, "Woof"), breed_(breed) {}
std::string speak() const override {
return Animal::speak() + '!';
}
};A call through the base interface selects the derived override at runtime.
Define arithmetic for a class
// Operator overloading
struct Vector2 {
double x, y;
Vector2 operator+(const Vector2& o) const { return {x+o.x, y+o.y}; }
bool operator==(const Vector2&) const = default; // C++20
};The addition overload lets two vectors produce a new vector using ordinary plus syntax.
RAII & Resource Management
RAII (Resource Acquisition Is Initialization) ties resource lifetime to object lifetime: acquire in the constructor, release in the destructor. This guarantees cleanup on any exit path — return, exception, or scope end — and is the foundation of every standard library resource type (unique_ptr, lock_guard, fstream).
Tie each acquired resource to an owning object. Its destructor runs when the scope ends, including when an exception exits the scope.
Observe cleanup during unwinding
The local owner is destroyed before the catch block runs. The program prints acquire, release, then caught. Remove the throw to see that ordinary scope exit also calls the destructor.
#include <iostream>
#include <stdexcept>
int main() {
struct Owner {
Owner() { std::cout << "acquire\n"; }
~Owner() { std::cout << "release\n"; }
};
try {
Owner owner;
throw std::runtime_error("example");
} catch (const std::runtime_error&) {
std::cout << "caught\n";
}
}Further examples
Own and release a file
// RAII: acquire resource in constructor, release in destructor
// Guarantees cleanup even on exceptions or early returns
#include <cstdio>
#include <mutex>
#include <memory>
#include <stdexcept>
#include <utility>
// File RAII wrapper — no leak regardless of exit path
class File {
FILE* handle_ = nullptr;
public:
explicit File(const char* path, const char* mode)
: handle_(std::fopen(path, mode)) {
if (!handle_) throw std::runtime_error("cannot open file");
}
~File() { if (handle_) std::fclose(handle_); }
// Non-copyable: two owners would double-close
File(const File&) = delete;
File& operator=(const File&) = delete;
// Movable: transfer sole ownership
File(File&& o) noexcept : handle_(o.handle_) { o.handle_ = nullptr; }
File& operator=(File&& o) noexcept {
if (this != &o) { if (handle_) std::fclose(handle_); handle_ = o.handle_; o.handle_ = nullptr; }
return *this;
}
FILE* get() const { return handle_; }
bool ok() const { return handle_ != nullptr; }
};A file wrapper pairs acquisition with a destructor that closes the file on scope exit.
Release locks and run scope cleanup
// Use the relevant declarations and includes from the preceding fragment.
// Mutex RAII: lock_guard / unique_lock
std::mutex mtx;
void thread_safe_work() {
std::lock_guard<std::mutex> guard(mtx); // locked here
// ...
} // unlocked here — even on exception
// ScopeGuard: run arbitrary cleanup at scope exit
template<typename F>
class ScopeGuard {
F fn_;
bool active_ = true;
public:
explicit ScopeGuard(F f) : fn_(std::move(f)) {}
~ScopeGuard() { if (active_) fn_(); }
void dismiss() { active_ = false; }
ScopeGuard(const ScopeGuard&) = delete;
ScopeGuard& operator=(const ScopeGuard&) = delete;
};
template<typename F> ScopeGuard<F> make_scope_guard(F f) { return ScopeGuard<F>{std::move(f)}; }
// Usage
void with_temp_file() {
auto guard = make_scope_guard([]{ std::remove("tmp.bin"); });
// ... write to tmp.bin ...
// guard fires on any exit path: return, throw, or fall-through
}
// Smart pointers = RAII in the standard library
auto p = std::make_unique<int>(42); // unique ownership
auto sp1 = std::make_shared<int>(99); // shared ownership
auto sp2 = sp1; // ref-count 2
// freed automatically when all owners go out of scopeA lock guard unlocks when it is destroyed. A scope guard applies the same idea to a cleanup callback.
Memory & Smart Pointers
RAII ties cleanup to object lifetime. unique_ptr expresses exclusive ownership and shared_ptr maintains shared ownership; raw pointers can represent non-owning access.
flowchart LR
Construct["Construct owner"] -->|acquire| Resource["Owned resource"]
Resource -->|use within lifetime| Scope["Owner remains alive"]
Scope -->|normal exit or unwinding| Destroy["Destructor releases resource"]A unique pointer expresses exclusive ownership. Moving it transfers that ownership. Use a shared pointer only when independent owners need to keep the same object alive.
Observe a shared object weakly
The weak pointer leaves the ownership count unchanged. After the last owner releases the object, lock returns an empty shared pointer.
#include <memory>
auto owner = std::make_shared<int>(42);
std::weak_ptr<int> observer = owner;
owner.reset();
auto access = observer.lock();Choose smart pointer ownership
#include <memory>
// unique_ptr — sole ownership, zero overhead
auto p = std::make_unique<int>(42);
auto p2 = std::move(p); // transfer ownership; p is now nullptr
// Custom deleter
auto file_ptr = std::unique_ptr<FILE, decltype(&fclose)>(
fopen("data.bin", "rb"), &fclose
);
// shared_ptr — shared ownership, ref-counted
auto sp1 = std::make_shared<std::string>(3, 'x');
auto sp2 = sp1; // ref count = 2
sp1.use_count(); // 2
// weak_ptr — non-owning observer, breaks cycles
std::weak_ptr<std::string> wp = sp1;
if (auto locked = wp.lock()) { // safe: lock() returns nullptr if expired
std::cout << *locked << '\n';
}unique_ptr owns exclusively, shared_ptr shares ownership, and weak_ptr observes without extending lifetime.
Tie resource lifetime to scope
// Use the relevant declarations and includes from the preceding fragment.
// Stack vs heap
std::vector<int> v(100); // heap storage, stack handle (RAII)
std::array<int, 100> arr{}; // fixed-size on stack
// RAII wrapper pattern
class FileHandle {
FILE* f_;
public:
explicit FileHandle(const char* path) : f_(fopen(path, 'r')) {}
~FileHandle() { if (f_) fclose(f_); }
FILE* get() const { return f_; }
};The wrapper’s destructor releases the resource when the wrapper leaves scope.
Move Semantics
Move operations allow resources to transfer between objects. std::move enables move overload selection rather than performing a transfer itself; observe the moved-from object's contract before reuse.
Std::move enables selection of a move operation by casting its argument to an rvalue. The selected constructor or assignment does the actual transfer. A moved-from standard library object is generally valid with an unspecified state.
Track exclusive ownership
After the move, the destination owns the integer and the source unique_ptr is empty. That emptiness is guaranteed for unique_ptr. A moved-from vector has a valid but generally unspecified state.
The move example prints 42 and true.
#include <iostream>
#include <memory>
#include <utility>
int main() {
auto source = std::make_unique<int>(42);
auto destination = std::move(source);
std::cout << *destination << '\n';
std::cout << std::boolalpha << (source == nullptr) << '\n';
}Further examples
Transfer ownership with a move
#include <algorithm>
#include <cstddef>
#include <utility>
#include <vector>
// lvalue (has address) vs rvalue (temporary)
int x = 42; // x is lvalue
int y = x + 1; // (x + 1) is rvalue expression
// std::move — casts to rvalue reference, enabling move
std::vector<int> a{1, 2, 3};
std::vector<int> b = std::move(a); // a remains valid; its state is unspecified
// Move constructor and move assignment (C++11)
class Buffer {
int* data_;
std::size_t size_;
public:
explicit Buffer(std::size_t n) : data_(new int[n]{}), size_(n) {}
~Buffer() { delete[] data_; }
// Copy constructor
Buffer(const Buffer& o) : data_(new int[o.size_]), size_(o.size_) {
if (size_ != 0) std::copy_n(o.data_, size_, data_);
}
// Move constructor — transfer ownership, leave source empty
Buffer(Buffer&& o) noexcept // C++11
: data_(o.data_), size_(o.size_) {
o.data_ = nullptr; o.size_ = 0;
}
// Move assignment
Buffer& operator=(Buffer&& o) noexcept { // C++11
if (this != &o) {
delete[] data_;
data_ = o.data_; size_ = o.size_;
o.data_ = nullptr; o.size_ = 0;
}
return *this;
}
};std::move enables move overloads. The buffer transfers its allocation and clears the source pointer.
Preserve value category in a wrapper
#include <utility>
// Perfect forwarding — preserve lvalue/rvalue category
template<typename T>
void wrapper(T&& arg) {
process(std::forward<T>(arg)); // C++11
}std::forward lets the wrapped call distinguish lvalues from rvalues.
Exceptions
Exceptions propagate failures while stack unwinding destroys automatic objects. RAII protects cleanup, and exception guarantees describe the state left after failure.
Stack unwinding destroys fully constructed local objects as an exception leaves a scope. Catch by reference to retain the dynamic exception type and avoid a copy.
Catch at a recovery boundary
The exception skips the rest of the try block and selects the matching handler. Recovered becomes true.
#include <stdexcept>
bool recovered = false;
try { throw std::out_of_range("missing item"); }
catch (const std::out_of_range&) { recovered = true; }Catch and classify exceptions
#include <stdexcept>
// try / catch hierarchy — most-derived first
try {
throw std::runtime_error("something went wrong");
} catch (const std::invalid_argument& e) {
std::cerr << "Invalid: " << e.what() << '\n';
} catch (const std::out_of_range& e) {
std::cerr << "Range: " << e.what() << '\n';
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << '\n';
} catch (...) {
std::cerr << "Unknown error\n";
}
// Custom exception
class AppError : public std::runtime_error {
int code_;
public:
AppError(const std::string& msg, int code)
: std::runtime_error(msg), code_(code) {}
int code() const { return code_; }
};
throw AppError("not found", 404);Catch more specific exception types first so a base handler does not intercept them.
State exception guarantees and release resources
// noexcept — declares function will not throw
void safe_swap(int& a, int& b) noexcept {
int tmp = a; a = b; b = tmp;
}
// noexcept(expr) — conditional noexcept
template<typename T>
void move_if_possible(T& a, T& b) noexcept(std::is_nothrow_move_constructible_v<T>) {
T tmp = std::move(a); a = std::move(b); b = std::move(tmp);
}
// RAII — cleanup guaranteed via destructor (never leaks on exception)
class TxGuard {
DB& db_;
bool committed_ = false;
public:
TxGuard(DB& db) : db_(db) { db_.begin(); }
void commit() { db_.commit(); committed_ = true; }
~TxGuard() { if (!committed_) db_.rollback(); }
};A noexcept declaration promises that no exception escapes. RAII releases objects during stack unwinding.
optional & variant (C++17)
optional models absence and variant stores one alternative from a fixed set. Check presence or visit the active alternative before accessing its contents.
An optional represents a value or absence. A variant holds one of several alternatives. Check the active alternative or use a visitor before accessing its contents.
Supply a fallback for absence
The absent limit yields 10. Assign 4 to limit and the same expression yields 4.
#include <optional>
std::optional<int> limit;
int effective = limit.value_or(10);Inspect the active alternative
The pointer refers to 2.5. Requesting int instead returns a null pointer.
#include <variant>
std::variant<int, double> reading = 2.5;
auto value = std::get_if<double>(&reading);Represent a missing value
#include <optional>
#include <variant> // C++17 throughout
// std::optional — value that may or may not exist
std::optional<int> maybe; // empty
maybe = 42; // assign
maybe.emplace(99); // construct in-place
if (maybe.has_value())
std::cout << *maybe << '\n'; // dereference
std::cout << maybe.value_or(0) << '\n'; // safe access with default
maybe.reset(); // back to empty
// Optional return pattern — cleaner than out-params or error codes
std::optional<int> divide(int a, int b) {
if (b == 0) return std::nullopt;
return a / b;
}
if (auto r = divide(10, 2)) std::cout << *r;Check whether the optional is engaged before dereferencing. value_or supplies a fallback.
Visit one of several alternatives
#include <iostream>
#include <string>
#include <variant>
// std::variant — type-safe union
std::variant<int, double, std::string> var = 42;
var = 3.14; // reassign different type
// Access with std::get / std::get_if
if (std::holds_alternative<double>(var))
std::cout << std::get<double>(var) << '\n';
if (auto* p = std::get_if<int>(&var))
std::cout << *p;
// std::visit — apply visitor to active member
std::visit([](auto&& v){ std::cout << v << '\n'; }, var);
// Overloaded visitor pattern
struct Visitor {
void operator()(int i) const { std::cout << "int:" << i; }
void operator()(double d) const { std::cout << "dbl:" << d; }
void operator()(std::string s) const { std::cout << "str:" << s; }
};
std::visit(Visitor{}, var);A variant tracks the active type. get_if can probe it and visit dispatches to a matching callable.
expected (C++23)
expected holds either a successful result or a typed error. Callers inspect and propagate ordinary failures without requiring exceptions for that API.
An expected value contains either a result or an error payload. Check which it holds and handle the error branch before reading the successful result. The example requires C++23 library support.
Inspect a typed failure
In C++23, the boolean test selects the failure path before reading the error. Empty input is true in this example.
#include <expected>
enum class Error { empty };
std::expected<int, Error> result = std::unexpected(Error::empty);
bool empty_input = !result && result.error() == Error::empty;Inspect a value or error
#include <expected> // C++23
// std::expected<T, E> — value or error, no exception overhead
std::expected<int, std::string> parse_int(const std::string& s) {
try {
return std::stoi(s);
} catch (...) {
return std::unexpected("not a number");
}
}
// Check and access
auto r = parse_int("42");
if (r.has_value())
std::cout << "value: " << r.value() << '\n';
else
std::cout << "error: " << r.error() << '\n';
// Concise access with value_or
int n = parse_int("abc").value_or(-1); // -1 on errorAn expected result holds either a value or an error. Check which state is active before accessing it.
Chain fallible operations
// Use the relevant declarations and includes from the preceding fragment.
// Monadic operations (C++23)
auto result = parse_int("5")
.and_then([](int v) -> std::expected<int, std::string> {
if (v < 0) return std::unexpected("negative");
return v * 2;
})
.transform([](int v){ return v + 1; })
.or_else([](auto&&) -> std::expected<int, std::string> {
return 0; // default on error
});
// vs exceptions pattern
std::expected<int, int> safe_div(int a, int b) { // C++23
if (b == 0) return std::unexpected(-1); // error code -1
return a / b;
}
// Chain without try/catch
safe_div(10, 2)
.transform([](int v){ return v * 3; })
.and_then([](int v) -> std::expected<int, int> { return v; });and_then calls the next operation on success and propagates an error on failure.
std::filesystem (C++17)
std::filesystem provides portable path manipulation, directory traversal, and file operations. Use std::error_code overloads to avoid exceptions in performance-sensitive or recoverable-error paths.
A path describes a location. Filesystem operations can fail even after a prior existence check. Handle errors at the operation and use a scratch directory for writes.
Separate filename from its directory
The results are june.csv and .csv. These operations inspect the path itself and do not access the filesystem.
#include <filesystem>
std::filesystem::path path{"reports/june.csv"};
auto file = path.filename();
auto extension = path.extension();Inspect and traverse paths
#include <filesystem>
#include <fstream>
namespace fs = std::filesystem;
// Path manipulation (C++17)
fs::path p = "/home/user/docs/report.pdf";
auto parent = p.parent_path(); // /home/user/docs
auto name = p.filename(); // report.pdf
auto stem = p.stem(); // report
auto ext = p.extension(); // .pdf
auto full = p / "backup"; // append component
// File queries
bool ex = fs::exists(p);
bool reg = fs::is_regular_file(p);
bool dir = fs::is_directory(p);
auto sz = fs::file_size(p);
auto mtime = fs::last_write_time(p);
// Directory listing — flat
for (const auto& entry : fs::directory_iterator("/tmp")) {
if (entry.is_regular_file())
std::cout << entry.path().filename() << '\n';
}
// Recursive listing — filter by extension
for (const auto& entry : fs::recursive_directory_iterator(".")) {
if (entry.path().extension() == ".cpp")
std::cout << entry.path().string() << '\n';
}A path composes names, and directory iterators visit entries in a directory tree.
Modify paths and handle errors
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
// Filesystem operations
fs::create_directories("a/b/c"); // like mkdir -p
fs::copy("src.txt", "dst.txt");
fs::rename("old.txt", "new.txt");
fs::remove("file.txt");
fs::remove_all("dir/"); // recursive delete
// Error handling without exceptions
std::error_code ec;
fs::remove_all("dir/", ec);
if (ec) std::cerr << ec.message() << '\n';
// Temp path
auto tmp = fs::temp_directory_path() / "scratch.bin";Use an error_code overload when the caller needs to branch on failure without catching an exception.
std::format & Chrono (C++20)
std::format provides Python-style format strings with compile-time format-string checking (C++23). <chrono> offers type-safe duration arithmetic and calendar types.
The format string controls how arguments appear without changing their stored values. A chrono duration combines a count and a unit, so preserve the unit when converting or printing it.
Convert a duration with units
The integer seconds count is 1. The explicit conversion discards the remaining 500 milliseconds.
#include <chrono>
auto delay = std::chrono::milliseconds{1500};
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(delay);Format values as text
#include <format>
#include <string>
// std::format (C++20) — type-safe, extensible printf replacement
std::string s1 = std::format("Hello, {}!", "world");
std::string s2 = std::format("{:>10}", "right"); // right-align in 10
std::string s3 = std::format("{:.2f}", 3.14159); // '3.14'
std::string s4 = std::format("{:#010x}", 255); // '0x000000ff'
std::string s5 = std::format("{0} {1} {0}", 'A', 'B'); // 'A B A' by index
// std::println (C++23) — format + write + newline
// With C++23 and <print>: std::println("Answer: {}", 42);Replacement fields insert arguments according to the format specification. println also writes a newline.
Measure time and format custom values
#include <chrono>
#include <format>
#include <iostream>
#include <string>
using namespace std::chrono;
using namespace std::chrono_literals;
// Chrono — durations and clocks (C++11, extended in C++20)
auto elapsed = 1h + 30min + 45s;
auto ms = duration_cast<milliseconds>(elapsed);
std::cout << ms.count() << " ms\n"; // 5445000 ms
// Measure wall time
auto t0 = steady_clock::now();
// ... work ...
auto dt = duration_cast<microseconds>(steady_clock::now() - t0);
std::cout << dt.count() << " us\n";
// Calendar types (C++20)
auto today = year_month_day{floor<days>(system_clock::now())};
std::cout << std::format("{}\n", today); // current UTC date
// Custom formatter — implement std::formatter<T>
struct Point { int x, y; };
template<>
struct std::formatter<Point> {
constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }
auto format(const Point& p, format_context& ctx) const {
return std::format_to(ctx.out(), "({}, {})", p.x, p.y);
}
};
std::string s = std::format("{}", Point{3, 4}); // '(3, 4)'Use a steady clock for elapsed time and calendar types for dates. A formatter specialization defines the text for a custom type.
Templates
Templates describe families of functions or types instantiated with concrete arguments. Make requirements clear so instantiation failures are understandable.
A template is instantiated with specific arguments. Keep definitions available where instantiation occurs, and express the operations the body expects from its type parameters.
Deduce a type from arguments
Calling larger with 2 and 5 deduces int and returns 5. Two different argument types can prevent deduction of a single T.
template<class T>
T larger(T a, T b) { return a < b ? b : a; }Parameterize functions and classes
// Function template — type deduced from arguments
template<typename T>
T max_val(T a, T b) { return (a > b) ? a : b; }
max_val(3, 7); // T = int
max_val(1.5, 2.5); // T = double
// Class template
template<typename T, std::size_t N>
class FixedArray {
T data_[N]{};
public:
T& operator[](std::size_t i) { return data_[i]; }
const T& operator[](std::size_t i) const { return data_[i]; }
constexpr std::size_t size() const { return N; }
};
FixedArray<int, 5> arr;
arr[0] = 42;Function arguments can deduce the template type. A class template uses that type for its stored values.
Specialize and parameterize by value
// Template specialization
template<typename T>
struct TypeName { static const char* name() { return "unknown"; } };
template<>
struct TypeName<int> { static const char* name() { return "int"; } };
// Non-type template parameters
template<int N>
constexpr int power_of_two = 1 << N;
static_assert(power_of_two<10> == 1024);
// Template aliases (C++11)
template<typename T> // C++11
using Vec = std::vector<T>;
Vec<int> v{1, 2, 3};A specialization supplies different behavior for a specific type. A value parameter can set an array size at compile time.
Variadic Templates
Variadic templates accept parameter packs. Expansions and fold expressions operate across a pack without manually defining each possible arity.
A parameter pack represents zero or more arguments. Expanding it substitutes each argument into a pattern. Check the empty pack when an operation needs at least one value.
Count arguments without inspecting them
Calling count with an integer and a character returns 2. Calling it with no arguments returns 0.
template<class... Ts>
constexpr auto count(Ts...) { return sizeof...(Ts); }Count and expand a parameter pack
// Parameter pack (C++11)
template<typename... Args>
void print_all(Args&&... args) { // C++11
(std::cout << ... << args); // fold expression (C++17)
}
print_all(1, ' ', 3.14, '\n');
// sizeof... — number of arguments in a pack
template<typename... Ts>
constexpr std::size_t count() { return sizeof...(Ts); }
static_assert(count<int, double, char>() == 3);
// Recursive variadic (C++11, pre-fold style)
void print_r() {} // base case — ends recursion
template<typename T, typename... Rest>
void print_r(T first, Rest... rest) { // C++11
std::cout << first << ' ';
print_r(rest...); // peel one argument
}sizeof... reports the pack size. A recursive expansion consumes one argument on each call.
Fold or forward a pack
// Use the relevant declarations and includes from the preceding fragment.
// Fold expressions (C++17)
template<typename... Ns>
auto sum(Ns... ns) { return (0 + ... + ns); } // left fold // C++17
template<typename... Ns>
auto product(Ns... ns) { return (1 * ... * ns); }
template<typename... Ts>
bool all_true(Ts... bs) { return (... && bs); } // unary left fold
// Forwarding a pack
template<typename T, typename... Args>
T create(Args&&... args) {
return T(std::forward<Args>(args)...); // perfect-forward each arg
}
// Expand into braced-init (pre-C++17 trick)
template<typename... Ts>
void process_all(Ts&&... args) {
int dummy[] = { (process(std::forward<Ts>(args)), 0)... };
(void)dummy;
}A fold combines pack elements with an operator. Forwarding expands each argument with its original value category.
Fold Expressions (C++17)
Fold expressions collapse a parameter pack into a single value using a binary operator. They supersede the recursive variadic template idiom for arithmetic reductions and function application.
A fold applies an operator across a pack. Its direction affects grouping for non-associative operators. Include an initial value when the empty case needs a defined result.
Define the empty result
The initial zero gives an empty call a result of 0. Calling total with 2 and 3 yields 5.
template<class... Ts>
auto total(Ts... values) { return (0 + ... + values); }Reduce a pack with an operator
// C++17 — reduce a parameter pack with a binary operator
// (pack op ...) — right fold
// (... op pack) — left fold
// (pack op ... op init) — right fold with init
// (init op ... op pack) — left fold with init
template<typename... Ts>
auto sum(Ts... args) {
return (args + ...); // left fold: ((a + b) + c) + d
}
template<typename... Ts>
auto product(Ts... args) {
return (... * args);
}Fold direction controls grouping. An initial value can define the result for an empty pack.
Short-circuit and sequence pack operations
// Use the relevant declarations and includes from the preceding fragment.
// && / || fold — short-circuit preserved
template<typename... Ts>
bool all_positive(Ts... args) { return ((args > 0) && ...); }
template<typename... Ts>
bool any_zero(Ts... args) { return ((args == 0) || ...); }
// Comma fold — invoke a callable for each element
template<typename F, typename... Ts>
void for_each_arg(F f, Ts&&... args) {
(f(std::forward<Ts>(args)), ...);
}
// << fold — variadic print
template<typename... Ts>
void print(Ts&&... args) {
(std::cout << ... << args);
std::cout << '\n';
}
// Sizeof... — count pack elements at compile time
template<typename... Ts>
constexpr std::size_t count() { return sizeof...(Ts); }
// Usage
sum(1, 2, 3, 4, 5); // 15
product(2, 3, 4); // 24
all_positive(1, 2, 3); // true
print("hello", ' ', 42); // hello 42Logical folds preserve short-circuiting. A comma fold invokes the operation for each argument in order.
Concepts (C++20)
Concepts express compile-time requirements for template arguments. They constrain overloads and improve diagnostics without validating runtime values.
A concept constrains which arguments match a template. When an argument fails a requirement, the compiler can reject the overload before instantiating its body.
Constrain an argument type
In C++20, doubled accepts 3 and returns 6. A double fails the integral constraint during overload selection.
#include <concepts>
auto doubled(std::integral auto value) { return value + value; }Define and check a concept
#include <concepts> // C++20
// Define a concept — predicate evaluated at compile time
template<typename T>
concept Printable = requires(T x) { // C++20
std::cout << x; // must be valid expression
};
// requires expression — checks multiple operations
template<typename T>
concept Container = requires(T c) {
c.begin();
c.end();
c.size();
typename T::value_type;
};
// Concept with return-type constraint
template<typename T>
concept Hashable = requires(T v) {
{ std::hash<T>{}(v) } -> std::convertible_to<std::size_t>;
};A requires expression checks that operations are valid and can constrain their result types.
Apply and combine constraints
// Use the relevant declarations and includes from the preceding fragment.
// Built-in standard concepts
template<std::integral T>
T double_it(T x) { return x * 2; }
template<std::floating_point T>
T half(T x) { return x / 2; }
// requires clause — inline constraint
template<typename T>
requires std::integral<T> || std::floating_point<T>
T square(T x) { return x * x; }
// Constrained auto (abbreviated function template)
auto add(std::integral auto a, std::integral auto b) { return a + b; }
void print(Printable auto x) { std::cout << x << '\n'; }
// Combining concepts
template<typename T>
concept Number = std::integral<T> || std::floating_point<T>;
template<Number T>
T clamp(T val, T lo, T hi) { return val < lo ? lo : val > hi ? hi : val; }Use standard concepts or combine predicates to state which types an overload accepts.
Type Traits & SFINAE
The <type_traits> header provides compile-time predicates and type transformations. SFINAE (via enable_if) and if constexpr let you branch on type properties at compile time — concepts (C++20) replace most SFINAE use cases with cleaner syntax.
Type traits expose properties at compile time. Substitution failure can remove an overload candidate when substituting arguments into its immediate context is invalid.
Inspect a type at compile time
Both assertions pass during compilation. The trait describes the type without inspecting a runtime value.
#include <type_traits>
static_assert(std::is_integral_v<int>);
static_assert(!std::is_integral_v<double>);Query and transform types
#include <type_traits>
// Type queries — evaluate to true/false at compile time
static_assert(std::is_integral_v<int>);
static_assert(std::is_floating_point_v<double>);
static_assert(!std::is_pointer_v<int>);
static_assert(std::is_same_v<int, int>);
// Type transformations
using T1 = std::remove_const_t<const int>; // int
using T2 = std::add_pointer_t<int>; // int*
using T3 = std::decay_t<int[3]>; // int*
using T4 = std::conditional_t<true, int, double>; // int
using T5 = std::common_type_t<int, double>; // doubleQueries expose compile-time facts. Transformations produce another type, such as one with its reference removed.
Select an implementation at compile time
#include <iterator>
#include <type_traits>
// SFINAE via enable_if (pre-C++20)
template<typename T>
std::enable_if_t<std::is_arithmetic_v<T>, T>
square(T x) { return x * x; }
// if constexpr — cleaner branch-at-compile-time
template<typename T>
std::string to_str(T val) {
if constexpr (std::is_arithmetic_v<T>)
return std::to_string(val);
else
return std::string(val);
}
// Tag dispatch — select overload by iterator category
template<typename Iter>
void advance_impl(Iter& it, int n, std::random_access_iterator_tag) {
it += n; // O(1)
}
template<typename Iter>
void advance_impl(Iter& it, int n, std::input_iterator_tag) {
while (n--) ++it; // O(n)
}
template<typename Iter>
void my_advance(Iter& it, int n) {
using Cat = typename std::iterator_traits<Iter>::iterator_category;
advance_impl(it, n, Cat{});
}A constraint or tag can select an overload. if constexpr discards the unused branch during instantiation.
Operator Overloading
Operator overloading lets user-defined types participate in expressions with natural syntax. Member operators receive the left operand implicitly; non-member (friend) operators are needed when the left operand is not your type. C++20's spaceship operator <=> auto-generates all six comparison operators from a single definition.
Use operator syntax when the operation has the meaning readers expect from built-in types. Keep related comparisons or arithmetic operations consistent.
Give addition a predictable meaning
Adding distances of 2 and 3 meters produces 5 meters. The operands retain their original values.
struct Distance { int meters; };
Distance operator+(Distance a, Distance b) { return {a.meters + b.meters}; }Define operators for vector arithmetic
#include <iostream>
#include <compare>
// Operator overloading: give user-defined types natural syntax
struct Vec2 {
double x, y;
// Arithmetic
Vec2 operator+(const Vec2& o) const { return {x + o.x, y + o.y}; }
Vec2 operator-(const Vec2& o) const { return {x - o.x, y - o.y}; }
Vec2 operator*(double s) const { return {x * s, y * s}; }
Vec2& operator+=(const Vec2& o) { x += o.x; y += o.y; return *this; }
// Unary minus
Vec2 operator-() const { return {-x, -y}; }
// Spaceship operator — auto-generates all six comparisons (C++20)
auto operator<=>(const Vec2&) const = default; // C++20
bool operator==(const Vec2&) const = default;
// Stream output — free function to allow cout on the left
friend std::ostream& operator<<(std::ostream& os, const Vec2& v) {
return os << '(' << v.x << ',' << v.y << ')';
}
};
// Non-member scalar multiplication: s * v
Vec2 operator*(double s, const Vec2& v) { return v * s; }The non-member overload supports scalar multiplication when the scalar appears on the left.
Implement indexing, calls and conversions
// Use the relevant declarations and includes from the preceding fragment.
// Subscript operator
struct Matrix2x2 {
double data[2][2]{};
double* operator[](int i) { return data[i]; }
const double* operator[](int i) const { return data[i]; }
};
// Call operator — makes objects callable (functor / closure alternative)
struct Adder {
int base;
int operator()(int x) const { return base + x; }
};
Adder add5{5};
int result = add5(10); // 15
// Conversion operator
struct Celsius {
double deg;
explicit operator double() const { return deg; } // explicit prevents implicit conversion
};
// Usage
Vec2 a{1, 2}, b{3, 4};
Vec2 c = a + b; // {4, 6}
Vec2 d = 2.0 * a; // {2, 4}
std::cout << c << '\n'; // (4,6)
bool eq = (a == a); // trueThese overloads let an object participate in subscript, call and conversion expressions.
Virtual Dispatch & vtable
Virtual dispatch implements runtime polymorphism: the compiler builds a vtable (a per-class array of function pointers) and stores a hidden vptr in each polymorphic object. Calling a virtual function follows the vptr to the vtable and then calls the correct override. Marking a class final or a call final lets the compiler devirtualize when the type is known.
A virtual call through a base reference uses the actual object’s override. Copying the object into a base value can slice away its derived part.
Call through a base reference
The reference refers to a Derived object, so the call returns 2.
struct Base { virtual int value() const { return 1; } };
struct Derived : Base { int value() const override { return 2; } };
Derived object;
const Base& view = object;
int result = view.value();Call overrides through base pointers
// Virtual dispatch: runtime selection of the correct overridden method
// Compilers commonly implement this with a vtable and an object pointer to it.
#include <memory>
#include <vector>
class Shape {
public:
virtual ~Shape() = default; // MUST be virtual for correct delete
virtual double area() const = 0; // pure virtual — Shape is abstract
virtual double perimeter() const = 0;
virtual std::string name() const { return "Shape"; } // optional override
};
class Circle : public Shape {
double r_;
public:
explicit Circle(double r) : r_(r) {}
double area() const override { return 3.14159265 * r_ * r_; }
double perimeter() const override { return 2 * 3.14159265 * r_; }
std::string name() const override { return "Circle"; }
};
class Rect : public Shape {
double w_, h_;
public:
Rect(double w, double h) : w_(w), h_(h) {}
double area() const override { return w_ * h_; }
double perimeter() const override { return 2 * (w_ + h_); }
std::string name() const override { return "Rect"; }
};
// Polymorphic container: store by pointer-to-base
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(5.0));
shapes.push_back(std::make_unique<Rect>(3.0, 4.0));
for (const auto& s : shapes)
std::cout << s->name() << " area=" << s->area() << '\n';
// Correct virtual dispatch — no switch, no castA virtual call selects the override using the object’s dynamic type.
Constrain overrides and expose a stable interface
// Use the relevant declarations and includes from the preceding fragment.
// final: prevent further overriding / inheritance
class Square final : public Rect {
public:
explicit Square(double side) : Rect(side, side) {}
// cannot be subclassed (compiler can devirtualize calls)
};
// Checking dynamic type at runtime
Shape* p = shapes[0].get();
if (auto* c = dynamic_cast<Circle*>(p)) {
std::cout << "Is a circle, r=" << c->area() << '\n';
}
// Non-virtual interface (NVI) pattern: public non-virtual, private virtual
class Logger {
public:
void log(const std::string& msg) { do_log("[LOG] " + msg); } // non-virtual
private:
virtual void do_log(const std::string& msg) { std::cout << msg << '\n'; }
};final closes an override point. A non-virtual public method can coordinate a private virtual hook.
Type Erasure
Type erasure hides a concrete type behind a uniform interface, enabling heterogeneous collections without a common base class. The standard library uses it in std::function and std::any. The virtual concept/model idiom replicates this pattern for custom value-semantic wrappers.
An erased wrapper exposes a fixed set of operations while hiding the concrete implementation type. Decide whether the wrapper owns the wrapped object or borrows it.
Store different callables behind one signature
The caller uses the same signature for both closures. The results are 5 and 8.
#include <functional>
std::function<int(int)> apply = [](int n) { return n + 1; };
int first = apply(4);
apply = [](int n) { return n * 2; };
int second = apply(4);Store callables and values through standard wrappers
// Type erasure: store objects of different types behind a uniform interface
// without exposing concrete types to callers.
// std::function and std::any are standard examples.
#include <functional>
#include <any>
#include <memory>
#include <vector>
// --- std::function: type-erases any callable ---
std::function<int(int, int)> op;
op = [](int a, int b){ return a + b; };
op = std::plus<int>{}; // function object
op(3, 4); // 7
// --- std::any: type-erases any CopyConstructible value ---
#include <any>
std::any a = 42;
a = std::string("hello");
std::cout << std::any_cast<std::string>(a) << '\n';
if (auto* p = std::any_cast<int>(&a)) std::cout << *p; // null if wrong typestd::function preserves a call signature and std::any preserves the stored value’s type for checked retrieval.
Erase a custom interface
// Use the relevant declarations and includes from the preceding fragment.
// --- Manual type erasure via virtual concept/model idiom ---
// Erase: all Drawable types, no inheritance required
struct DrawConcept {
virtual ~DrawConcept() = default;
virtual void draw() const = 0;
virtual std::unique_ptr<DrawConcept> clone() const = 0;
};
template<typename T>
struct DrawModel : DrawConcept {
T obj;
explicit DrawModel(T o) : obj(std::move(o)) {}
void draw() const override { obj.draw(); }
std::unique_ptr<DrawConcept> clone() const override {
return std::make_unique<DrawModel<T>>(obj);
}
};
class Drawable {
std::unique_ptr<DrawConcept> concept_;
public:
template<typename T>
Drawable(T obj) : concept_(std::make_unique<DrawModel<T>>(std::move(obj))) {}
Drawable(const Drawable& o) : concept_(o.concept_->clone()) {}
void draw() const { concept_->draw(); }
};
// Concrete types — no common base class needed
struct Circle { double r; void draw() const { std::cout << "O\n"; } };
struct Star { int pts; void draw() const { std::cout << "*\n"; } };
std::vector<Drawable> scene;
scene.emplace_back(Circle{5.0});
scene.emplace_back(Star{6});
for (const auto& d : scene) d.draw();The model stores the concrete value and forwards drawing through a common virtual interface.
CRTP (C++11)
CRTP (Curiously Recurring Template Pattern) has a base class template accept its derived class as a type parameter. The base can call derived methods via static_cast without virtual dispatch, enabling zero-overhead static polymorphism, mixin composition, and per-class counters.
The derived class passes its own type to the base template. This gives the base access to derived behavior through compile-time dispatch.
Call derived behavior from a template base
The derived type is known when the base template is instantiated. Run calls Task::value and returns 7.
template<class Derived>
struct Base { int run() { return static_cast<Derived&>(*this).value(); } };
struct Task : Base<Task> { int value() { return 7; } };
int result = Task{}.run();Dispatch through a derived template parameter
// CRTP: Curiously Recurring Template Pattern
// Base<Derived> accepts the derived class as a template argument,
// enabling static (compile-time) polymorphism with zero virtual overhead.
#include <iostream>
#include <cmath>
// Base provides shared interface, calls into Derived via static_cast
template<typename Derived>
class Shape {
public:
// CRTP dispatch — no virtual, resolved at compile time
double area() const { return static_cast<const Derived*>(this)->area_impl(); }
double perimeter() const { return static_cast<const Derived*>(this)->perimeter_impl(); }
// Shared implementation built on the customisation points
bool larger_than(const Shape& other) const {
return area() > other.area();
}
void print() const {
std::cout << "area=" << area() << " peri=" << perimeter() << '\n';
}
};
class Circle : public Shape<Circle> {
double r_;
public:
explicit Circle(double r) : r_(r) {}
double area_impl() const { return 3.14159 * r_ * r_; }
double perimeter_impl() const { return 2 * 3.14159 * r_; }
};
class Rect : public Shape<Rect> {
double w_, h_;
public:
Rect(double w, double h) : w_(w), h_(h) {}
double area_impl() const { return w_ * h_; }
double perimeter_impl() const { return 2 * (w_ + h_); }
};The base casts to its derived type to invoke the derived implementation at compile time.
Reuse behavior with a template mixin
// Use the relevant declarations and includes from the preceding fragment.
// CRTP mixin: add clone() to any class that provides copy construction
template<typename Derived>
class Cloneable {
public:
std::unique_ptr<Derived> clone() const {
return std::make_unique<Derived>(static_cast<const Derived&>(*this));
}
};
class Widget : public Cloneable<Widget> {
public:
int id;
explicit Widget(int i) : id(i) {}
};
auto w1 = Widget{42};
auto w2 = w1.clone(); // std::unique_ptr<Widget>
// CRTP counter: count instances per concrete type
template<typename T>
class Counter {
inline static int count_ = 0;
public:
Counter() { ++count_; }
~Counter() { --count_; }
static int count() { return count_; }
};
class Dog : public Counter<Dog> {};
class Cat : public Counter<Cat> {};
Dog d1, d2;
Cat c1;
std::cout << Dog::count() << '\n'; // 2
std::cout << Cat::count() << '\n'; // 1Each concrete type gets its own specialization, which can provide cloning behavior or maintain a separate counter.
Policy-Based Design
Policy-based design composes behaviour from interchangeable template-parameter classes called policies. Each policy governs one orthogonal concern (storage, threading, formatting). Because policies are resolved at compile time, the resulting class has no virtual overhead and the optimizer sees the full implementation.
A policy parameter chooses one part of the implementation at compile time. Keep its required operations small. To compare two policies, hold the input and calling code constant and observe the output when the policy type changes.
Select a rule at compile time
For input 3, the Double policy gives 6 and Increment gives 4. Both use the same score function template.
struct Double { static int apply(int n) { return n * 2; } };
struct Increment { static int apply(int n) { return n + 1; } };
template<class Policy>
int score(int n) { return Policy::apply(n); }Define interchangeable policies
// Policy-based design: compose behaviour from interchangeable policy classes.
// Policies are template parameters — selection is resolved at compile time,
// producing zero overhead compared to runtime polymorphism.
#include <iostream>
#include <fstream>
#include <string>
#include <mutex>
// --- Storage policy ---
struct HeapStorage {
static char* alloc(std::size_t n) { return new char[n]; }
static void free(char* p) { delete[] p; }
};
struct StackStorage {
static char* alloc(std::size_t) { return nullptr; } // simplified
static void free(char*) {}
};
// --- Locking policy ---
struct SingleThreaded {
struct Lock {};
Lock acquire() { return {}; }
};
struct MultiThreaded {
std::mutex m;
std::unique_lock<std::mutex> acquire() { return std::unique_lock<std::mutex>(m); }
};A policy supplies a focused operation such as storage or locking.
Assemble a logger from policies
// Use the relevant declarations and includes from the preceding fragment.
// --- Logger: accepts output and formatting policies ---
struct ConsoleOutput {
static void write(const std::string& msg) { std::cout << msg; }
};
struct FileOutput {
std::ofstream fs;
FileOutput() : fs("app.log", std::ios::app) {}
void write(const std::string& msg) { fs << msg; }
};
struct PlainFormat {
static std::string format(const std::string& msg) { return msg + '\n'; }
};
struct PrefixFormat {
static std::string format(const std::string& msg) { return "[LOG] " + msg + '\n'; }
};
template<typename OutputPolicy = ConsoleOutput,
typename FormatPolicy = PlainFormat,
typename ThreadPolicy = SingleThreaded>
class Logger : private OutputPolicy,
private FormatPolicy,
private ThreadPolicy {
public:
void log(const std::string& msg) {
auto lock = ThreadPolicy::acquire();
OutputPolicy::write(FormatPolicy::format(msg));
}
};
// Zero-cost instantiation — all policies inlined
Logger<> plain_logger;
Logger<ConsoleOutput, PrefixFormat> prefixed;
Logger<ConsoleOutput, PlainFormat, MultiThreaded> thread_safe;
plain_logger.log("hello"); // hello
prefixed.log("world"); // [LOG] worldUse the policy definitions from the preceding fragment. Template arguments select the behavior for each instantiation.
Concurrency
The standard threading library (<thread>, <mutex>, <atomic>, <future>) covers most concurrency needs. std::jthread (C++20) adds cooperative cancellation via stop tokens and automatic joining.
Arrange for each thread to finish or be joined according to its ownership contract. Shared state needs a consistent synchronization policy even when completion is tracked separately.
Read results after joining
Joining waits for a worker to finish. The mutex protects concurrent changes to the shared vector while workers are active. Join every worker before using the complete result in the caller.
Join before reading a worker result
After join returns, the caller can read 42. The caller must avoid reading the shared result while the worker can still write it.
#include <thread>
int result = 0;
std::thread worker([&result] { result = 42; });
worker.join();Coordinate shared state
#include <thread>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <future>
#include <vector>
// std::atomic — atomic operations on shared state
std::atomic<int> counter{0};
void increment() {
for (int i = 0; i < 100'000; ++i)
counter.fetch_add(1, std::memory_order_relaxed);
}
// std::mutex + lock_guard (RAII)
std::mutex mtx;
std::vector<int> results;
void worker(int id) {
std::lock_guard lock{mtx}; // C++17 CTAD
results.push_back(id);
}
// condition_variable — notify between threads
std::condition_variable cv;
bool ready = false;
void producer() {
{ std::lock_guard lk{mtx}; ready = true; }
cv.notify_all();
}
void consumer() {
std::unique_lock lk{mtx};
cv.wait(lk, []{ return ready; }); // recheck the predicate after waking
}Use atomics for individual operations and a mutex for related state. A condition-variable wait checks a predicate under the lock.
Retrieve results and join workers
// Use the relevant declarations and includes from the preceding fragment.
// std::async + future — fire-and-get
auto fut = std::async(std::launch::async, []{ return 42; });
int result = fut.get(); // blocks until ready
// std::jthread (C++20) — auto-joins, has stop token
#include <stop_token>
std::jthread bg([](std::stop_token tok) {
while (!tok.stop_requested()) { /* work */ }
});
bg.request_stop(); // or destructor stops it automatically
// Launch N threads
std::vector<std::thread> threads;
for (int i = 0; i < 4; ++i) threads.emplace_back(increment);
for (auto& t : threads) t.join();A future carries an asynchronous result. jthread joins at destruction and supports cooperative stop requests.
Coroutines (C++20)
Coroutines are functions that can suspend and resume execution. co_yield suspends and produces a value; co_await can suspend when the awaiter is not ready. A coroutine frame stores the state needed across suspension. A compiler can sometimes avoid a separate allocation for that frame.
Suspension preserves coroutine state for a later resume. Read the promise type and return object together to determine who controls resumption and who destroys the coroutine frame.
Pull values until completion
Place these calls in main with the Generator and range definitions below. The calls yield 2, then 3, then an empty optional.
auto numbers = range(2, 4);
auto first = numbers.next();
auto second = numbers.next();
auto done = numbers.next();Define a generator and producers
#include <coroutine>
#include <exception>
#include <iostream>
#include <optional>
#include <utility>
// C++20 — Generator that lazily yields values
template<typename T>
struct Generator {
struct promise_type {
T current_value;
std::suspend_always yield_value(T v) { current_value = v; return {}; }
std::suspend_always initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
Generator get_return_object() {
return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};
}
void return_void() {}
void unhandled_exception() { std::terminate(); }
};
explicit Generator(std::coroutine_handle<promise_type> h) : handle(h) {}
Generator(const Generator&) = delete;
Generator& operator=(const Generator&) = delete;
Generator(Generator&& other) noexcept : handle(std::exchange(other.handle, {})) {}
Generator& operator=(Generator&&) = delete;
~Generator() { if (handle) handle.destroy(); }
std::optional<T> next() {
if (!handle || handle.done()) return std::nullopt;
handle.resume();
if (handle.done()) return std::nullopt;
return handle.promise().current_value;
}
private:
std::coroutine_handle<promise_type> handle;
};
Generator<int> fibonacci() {
int a = 0, b = 1;
for (int i = 0; i < 10; ++i) {
co_yield a; // suspend here, save {a, b} on coroutine frame
auto tmp = a + b;
a = b;
b = tmp;
}
}
Generator<int> range(int from, int to) {
for (int i = from; i < to; ++i)
co_yield i;
}co_yield suspends the producer after publishing a value. The generator owns the coroutine handle.
Resume a producer from its caller
// Use the relevant declarations and includes from the preceding fragment.
// Caller drives execution — no OS thread needed
int main() {
auto gen = fibonacci();
while (auto value = gen.next()) std::cout << *value << ' ';
}
// 0 1 1 2 3 5 8 13 21 34Place this main after the generator definitions. The loop requests the next Fibonacci value until the generator finishes.
Modules (C++20)
C++20 modules replace the textual #include model with a compiled binary interface. Each module is compiled once; importers consume the precompiled interface rather than re-parsing headers. This eliminates macro leakage, reduces build times, and makes the dependency graph explicit and tooling-friendly.
Place the interface and importer in the files shown and use the module build procedure for your compiler. Only exported declarations are available through an import.
Separate the interface from its importer
Compile the module interface before its importer. The importer can call exported functions. Keep implementation helpers inside the module and follow the build commands for your compiler.
Export module interfaces
// Modules (C++20) replace #include with a cleaner dependency model.
// No header guard boilerplate, no macro leakage, faster build times.
// ---- math.cppm (module interface unit) ----
export module math; // declare this file as the 'math' module
import <cmath>; // import standard library header unit
export namespace math {
constexpr double PI = 3.14159265358979;
export double circle_area(double r) { return PI * r * r; }
export double hypotenuse(double a, double b) { return std::sqrt(a*a + b*b); }
export template<typename T>
T clamp(T val, T lo, T hi) {
return val < lo ? lo : val > hi ? hi : val;
}
} // namespace math
// Internal linkage — not exported, invisible outside this module
static double impl_detail(double x) { return x * x; }
// ---- geometry.cppm (module interface unit) ----
export module geometry;
export import math; // re-export math symbols to importers
export struct Point { double x, y; };
export double distance(Point a, Point b) {
return math::hypotenuse(b.x - a.x, b.y - a.y);
}Save the interfaces in the indicated files. Export exposes declarations to importers.
Import modules into a program
// ---- main.cpp ----
import math;
import geometry;
import <iostream>;
int main() {
std::cout << math::circle_area(5.0) << '\n'; // 78.5398...
Point p1{0, 0}, p2{3, 4};
std::cout << distance(p1, p2) << '\n'; // 5
// Module partition (split large module across files):
// export module math:algebra; // partition file
// import math:algebra; // use partition within module
}
// Build with: g++ -std=c++20 -fmodules-ts math.cppm geometry.cppm main.cpp
// Or with CMake 3.28+: target_sources(app PUBLIC FILE_SET CXX_MODULES FILES math.cppm)The main translation unit imports the earlier interfaces and uses their exported names.
Sanitizers & Debugging
Compiler sanitizers instrument code at build time to detect bugs at runtime with precise diagnostics. AddressSanitizer finds memory errors (buffer overflows, use-after-free); UBSan catches undefined behaviour; ThreadSanitizer detects data races; MemorySanitizer finds uninitialized reads. Combine with -g -O1 for useful stack traces without excessive slowdown.
Build and run the instrumented executable with representative inputs. A sanitizer report identifies behavior observed on an executed path. Additional paths still need coverage.
Read the first application frame
Build the example with debug information. In a sanitizer report, find the first frame in your source and compare that operation with the reported bounds or lifetime. Rebuild and rerun the same input after fixing it.
Diagnose invalid memory access and operations
// Sanitizers: compiler-injected instrumentation that detects bugs at runtime.
// Enable with compiler flags — no source changes needed.
// ---- AddressSanitizer (ASan): detect memory errors ----
// Compile with -fsanitize=address -fno-omit-frame-pointer -g.
#include <climits>
void asan_demo() {
int arr[5]{};
// arr[10] = 1; // stack-buffer-overflow
// int* p = new int(42); delete p; *p = 1; // use-after-free
}
// ---- UndefinedBehaviorSanitizer (UBSan): detect UB ----
// Compile with -fsanitize=undefined -g.
void ubsan_demo() {
int x = INT_MAX;
// x = x + 1; // signed integer overflow — UBSan fires
int arr[3]{};
// int y = arr[5]; // out-of-bounds — UBSan fires
void* p = nullptr;
// *static_cast<int*>(p) = 1; // null dereference
}AddressSanitizer checks memory access. UndefinedBehaviorSanitizer checks operations such as signed overflow.
Check races, initialization and layout assumptions
#include <cstdint>
// ---- ThreadSanitizer (TSan): detect data races ----
// Compile with -fsanitize=thread -g -pthread.
#include <thread>
int shared = 0;
void tsan_demo() {
std::thread t1([]{ shared++; }); // race on 'shared'
std::thread t2([]{ shared++; });
t1.join(); t2.join();
// TSan: data race on shared
}
// ---- MemorySanitizer (MSan): detect uninitialised reads ----
// Compile with Clang and -fsanitize=memory -g on a supported platform.
void msan_demo() {
int x;
// if (x > 0) ... // MSan: conditional jump on uninitialized value
}
// ---- Valgrind (external, no recompile needed) ----
// valgrind --leak-check=full ./app
// valgrind --tool=callgrind ./app # profiling
// ---- static_assert: compile-time checks ----
struct Packet { std::uint8_t type; std::uint16_t len; std::uint8_t payload[256]; };
static_assert(sizeof(Packet) == 260, "unexpected padding");
static_assert(alignof(double) == 8, "unexpected alignment");
// ---- Debugging tips ----
// Compile with: -g -O0 -DDEBUG
// Use: assert(), [[nodiscard]], -Wall -Wextra -Wpedantic
// Avoid UB: -ftrapv (trap signed overflow), -fstack-protector-strongThreadSanitizer detects races during execution. MemorySanitizer detects uninitialized reads, and static assertions check target assumptions during compilation.
Best Practices
Prefer Modern C++ Idioms
Use auto, range-for, structured bindings, emplace_back, std::array, nullptr, enum class, using aliases, override/final, and = delete/= default to write expressive, refactor-safe code.
Prefer an abstraction that expresses intent and lifetime. For example, use a container for owned elements and a view for borrowed access.
Name a closed set of states
The scoped enum keeps state names under State. Callers select a named state instead of passing an arbitrary integer.
enum class State { idle, running };
State state = State::idle;Use deduction and range traversal
// ── Prefer Modern C++ Idioms ──────────────────────────────────────────────
// auto: let the compiler deduce the type
auto v = std::vector<int>{1, 2, 3}; // ✓ not: std::vector<int> v = ...
auto it = v.begin(); // ✓ iterator type is fragile to refactor
// range-for instead of index loop
for (const auto& x : v) { /* read */ }
for (auto& x : v) { x *= 2; } // mutate
// structured bindings (C++17)
std::map<std::string, int> scores{{"Alice", 95}, {"Bob", 87}};
for (const auto& [name, score] : scores)
std::cout << name << ':' << score << '\n';
// emplace_back constructs in-place — no temporary
v.emplace_back(42); // ✓ not: v.push_back(42) (trivial here)
std::vector<std::pair<int,int>> pairs;
pairs.emplace_back(1, 2); // ✓ not: pairs.push_back({1, 2})auto infers a type from the initializer. A reference in a range-for can update elements in place.
Express intent in declarations
// std::array instead of C array — bounds, iterators, no decay
std::array<int, 5> arr{1, 2, 3, 4, 5}; // ✓ not: int arr[5] = {1,2,3,4,5}
// nullptr, not NULL or 0
int* p = nullptr; // ✓ not: int* p = NULL
// enum class — scoped, no implicit int conversion
enum class Color { Red, Green, Blue };
Color c = Color::Red; // ✓ not: enum Color { Red, Green, Blue }
// using alias instead of typedef — supports templates
using StringVec = std::vector<std::string>; // ✓ not: typedef std::vector<...>
// override / final — document and enforce overrides, catch typos
struct Base { virtual void draw() const; };
struct Derived : Base { void draw() const override; }; // ✓
// = delete / = default — express intent explicitly
struct NonCopyable {
NonCopyable(const NonCopyable&) = delete;
NonCopyable& operator=(const NonCopyable&) = delete;
NonCopyable() = default;
};Scoped enums qualify their values. override checks an intended override and deleted members forbid operations.
Resource Ownership & RAII
Own every resource through a smart pointer or an RAII wrapper. Follow the rule of zero when possible, the rule of five only when managing a raw resource. Prefer make_unique/make_shared and stack allocation over naked new/delete.
Represent exclusive ownership directly with an owning value or unique pointer. Give non-owning observers a lifetime no longer than the object they observe.
Let a value own its storage
The vector handles destruction, copying, and moving. Samples can use the compiler-generated operations.
#include <vector>
struct Samples { std::vector<int> values; };Select a resource owner
// ── Resource Ownership & RAII ─────────────────────────────────────────────
// ✓ unique_ptr — sole, non-sharing ownership, zero overhead
auto conn = std::make_unique<Connection>(host, port);
// conn freed automatically when it leaves scope — no naked delete
// ✓ shared_ptr — shared ownership via ref-count
auto cfg = std::make_shared<Config>();
auto copy = cfg; // ref-count 2; freed when last owner dies
// ✗ Avoid owning raw pointers
// Connection* conn = new Connection(host, port); // who deletes?
// ✓ make_unique / make_shared — exception-safe, single allocation
auto w = std::make_unique<Widget>(42);
auto s = std::make_shared<Session>(token);
// ✗ Never naked new/delete in application code
// Widget* w = new Widget(42); delete w; // easy to leakConstruction helpers create the owning smart pointer. Ownership determines when the resource is released.
Let members handle cleanup
// ✓ Rule of Zero — if you use smart pointers/standard containers
// the compiler-generated special members are correct
struct Config {
std::string name;
std::vector<int> values;
// no destructor, no copy/move needed — rule of zero
};
// ✓ Rule of Five — only when you manage a raw resource
class Buffer {
std::unique_ptr<int[]> data_;
std::size_t size_;
public:
explicit Buffer(std::size_t n) : data_(std::make_unique<int[]>(n)), size_(n) {}
// Copy, move, destructor all automatically correct via unique_ptr
};
// ✓ Prefer stack over heap for small, fixed-size objects
std::array<char, 256> local_buf{}; // stack
// not: auto buf = std::make_unique<char[]>(256); // unnecessary heap
// ✓ RAII wrapper for C resources
class FilePtr {
FILE* f_;
public:
explicit FilePtr(const char* path, const char* mode) : f_(std::fopen(path, mode)) {}
~FilePtr() { if (f_) std::fclose(f_); }
FILE* get() const { return f_; }
};The rule of zero lets resource-owning members supply destruction and copying behavior.
Template & Generic Code
Constrain templates with concepts (C++20) for readable error messages. Use if constexpr instead of SFINAE, provide meaningful static_assert messages, and use explicit template instantiation to control compile times.
State template constraints near the interface. Keep the shared algorithm independent of type-specific details when a parameter or policy can express the variation.
Explain a template requirement
Instantiating with int succeeds. Instantiating with double emits the requirement in the assertion message.
#include <type_traits>
template<class T>
void validate_counter_type() {
static_assert(std::is_integral_v<T>, "counter requires an integer");
}Express template requirements
// ── Template & Generic Code ───────────────────────────────────────────────
// ✓ Constrain with concepts (C++20) — clear errors, self-documenting
template<std::integral T>
T clamp(T v, T lo, T hi) { return v < lo ? lo : v > hi ? hi : v; }
// ✗ Unconstrained — confusing error 50 lines into instantiation
// template<typename T>
// T clamp(T v, T lo, T hi) { return v < lo ? lo : v > hi ? hi : v; }
// ✓ Custom concept
template<typename T>
concept Addable = requires(T a, T b) { { a + b } -> std::same_as<T>; };
template<Addable T>
T sum(T a, T b) { return a + b; }
// ✓ if constexpr — cleaner than SFINAE for compile-time branching
template<typename T>
std::string to_str(T val) {
if constexpr (std::is_arithmetic_v<T>)
return std::to_string(val);
else
return std::string(val);
}Concepts constrain admissible inputs. if constexpr selects the implementation that matches the type.
Diagnose and manage instantiation
// ✓ Meaningful static_assert messages
template<typename T>
void store(T val) {
static_assert(std::is_trivially_copyable_v<T>,
"store<T>: T must be trivially copyable for memcpy-based serialisation");
}
// ✓ Explicit template instantiation in .cpp — avoids re-instantiating in every TU
// In math.cpp:
// template int clamp<int>(int, int, int);
// In math.h:
// extern template int clamp<int>(int, int, int);
// ✓ Document template requirements in a comment when concepts are unavailable
// T must be LessThanComparable and DefaultConstructible
template<typename T>
T max_default(T a, T b) { return a < b ? b : a; }A static assertion explains a failed requirement. Explicit instantiation can centralize code generation for a supported type.
Error Handling
Reserve exceptions for truly exceptional conditions. Return std::optional for nullable results, std::expected for recoverable failures. Mark non-throwing functions noexcept, never throw from destructors, and catch by const reference.
Choose the error contract based on how callers recover. Preserve cleanup through owned objects and make ordinary failure cases easy to distinguish.
Give absence a name in the interface
The caller can distinguish an absent limit from a configured limit of 10 by checking the result.
#include <optional>
std::optional<int> find_limit(bool configured) {
if (!configured) return std::nullopt;
return 10;
}Choose a failure representation
// ── Error Handling ────────────────────────────────────────────────────────
// ✓ Exceptions for truly exceptional, unrecoverable conditions
void open_db(const std::string& path) {
if (!fs::exists(path))
throw std::runtime_error("database not found: " + path);
}
// ✓ std::optional for nullable / may-not-exist returns
std::optional<User> find_user(int id) {
if (auto it = db.find(id); it != db.end()) return it->second;
return std::nullopt;
}
if (auto u = find_user(42)) { /* use *u */ }
// ✓ std::expected for expected failures (C++23)
std::expected<int, std::string> parse(const std::string& s) {
try { return std::stoi(s); }
catch (...) { return std::unexpected("not a number: " + s); }
}
auto r = parse("abc");
if (!r) std::cerr << r.error();Use optional for absence, expected when the caller needs a reason, and exceptions for exceptional failures.
Preserve state on failure
// ✓ noexcept — annotate functions that provably cannot throw
void swap_vals(int& a, int& b) noexcept { std::swap(a, b); }
// ✗ NEVER throw from a destructor — terminates the program during stack unwind
struct Bad {
~Bad() { throw std::runtime_error("boom"); } // ✗ undefined behaviour
};
struct Good {
~Good() noexcept { /* clean up, log, but never throw */ }
};
// ✓ Catch by const reference — avoid slicing, avoid copy
try {
open_db("/missing");
} catch (const std::exception& e) { // ✓
std::cerr << e.what() << '\n';
}
// ✗ } catch (std::exception e) { // slices derived types
// ✓ Aim for the strong exception guarantee:
// if an operation throws, the program state is unchanged
std::vector<int> committed;
void append_atomic(std::vector<int>& v, int x) {
auto tmp = v; // copy first
tmp.push_back(x); // mutate copy — may throw
v = std::move(tmp); // commit: move is noexcept
}Catch by const reference to retain the dynamic type. Prepare changes before committing them to provide the strong guarantee.
Performance
Pass large objects by const&, return by value (trust NRVO), prefer pre-increment, reserve containers when size is known, use emplace over insert, and prefer string_view for read-only string parameters. Profile before optimising.
Measure a release build on representative data. Reserve capacity when growth is known to matter, then check the effect on allocations and latency.
Reserve before known growth
Capacity is at least 100 while size remains zero. Appending up to 100 elements fits without reallocating.
#include <vector>
std::vector<int> samples;
samples.reserve(100);Reduce copies and moves
// ── Performance ───────────────────────────────────────────────────────────
// ✓ Pass large objects by const ref — no copy
void process(const std::vector<double>& data) { /* ... */ }
// ✗ void process(std::vector<double> data) — copies every element
// ✓ Return by value — NRVO / RVO eliminates the copy in practice
std::vector<int> build_range(int n) {
std::vector<int> v;
v.reserve(n);
for (int i = 0; i < n; ++i) v.push_back(i);
return v; // NRVO: no copy, constructed directly in caller
}
// ✓ Pre-increment for non-trivial iterators
for (auto it = m.begin(); it != m.end(); ++it) { /* ... */ } // ✓ ++it
// ✗ it++ — creates a temporary for map/list iterators
// ✓ std::move to avoid unnecessary copies
std::string build_greeting(std::string name) {
name.insert(0, "Hello, ");
return std::move(name); // avoid copy of local (or just return name — NRVO)
}Pass large read-only inputs by reference and return constructed results by value.
Control allocations and measure bottlenecks
// ✓ reserve when size is known
std::vector<int> v;
v.reserve(1000); // single allocation, no reallocations
for (int i = 0; i < 1000; ++i) v.push_back(i);
// ✓ emplace over insert — construct in-place
std::map<int, std::string> m;
m.emplace(1, "one"); // ✓ not: m.insert({1, 'one'})
// ✓ string_view for read-only string parameters — accepts all string types, no alloc
void log_prefix(std::string_view prefix, std::string_view msg) {
std::cout << prefix << ": " << msg << '\n';
}
// ✓ Avoid virtual in hot paths — use CRTP or if constexpr instead
// ✗ Calling a virtual method in a tight loop prevents inlining and devirtualisation
// ✓ Profile before optimising
// Use: perf, Valgrind/Callgrind, gprof, or compiler flags -pg
// Premature micro-optimisation obscures intent; measure firstreserve can avoid growth reallocations. Profile the workload before changing a hot path.
Safety & Correctness
Enable -Wall -Wextra -Wpedantic and sanitizers (ASan/UBSan) in CI. Use [[nodiscard]], mark getters const, prefer std::span over pointer+size pairs, use .at() for bounds-checked access, and never silently discard [[nodiscard]] results.
Check the lifetime and bounds of borrowed data before access. Prefer an interface that carries the size along with the pointer when callers pass a buffer.
Choose a checked access
Only index zero is valid. The checked access throws and the handler runs.
#include <vector>
#include <stdexcept>
std::vector<int> values{7};
try { (void)values.at(1); }
catch (const std::out_of_range&) { /* handle the invalid index */ }Surface issues at build and test time
// ── Safety & Correctness ──────────────────────────────────────────────────
// ✓ Enable full warnings — treat them as errors in CI
// g++ -Wall -Wextra -Wpedantic -Werror -std=c++20
// ✓ Enable sanitizers in debug / CI builds
// g++ -fsanitize=address,undefined -fno-omit-frame-pointer -g
// g++ -fsanitize=thread -g
// ✓ [[nodiscard]] — force callers to check return values
[[nodiscard]] std::error_code write_file(const fs::path& p, std::string_view data);
[[nodiscard]] bool try_lock();
// Calling code must use the result — compiler warns otherwise
auto ec = write_file("out.bin", payload);
if (ec) std::cerr << ec.message() << '\n';
// ✓ Mark getters const
struct Vec2 {
double x, y;
double length() const { return std::sqrt(x*x + y*y); } // ✓ const
// double length() { ... } // ✗ cannot call on const Vec2
};Warnings and sanitizer runs expose different classes of defects. nodiscard lets the compiler diagnose discarded results.
Carry bounds and check access
// ✓ std::span instead of raw pointer + size
void fill_buffer(std::span<int> buf, int val) {
for (auto& x : buf) x = val;
}
std::array<int, 8> arr{};
fill_buffer(arr, 0); // ✓ span wraps the array safely
// ✓ Avoid signed/unsigned comparison — use consistent types
std::vector<int> v{1, 2, 3};
for (std::size_t i = 0; i < v.size(); ++i) { /* ... */ }
// ✗ for (int i = 0; i < v.size(); ...) — signed/unsigned mismatch warning
// ✓ Bounds-checked access in debug mode
int safe = v.at(2); // throws std::out_of_range if out of bounds
// int unsafe = v[2]; // UB if out of bounds — only ok when index is provably valid
// ✓ Never ignore [[nodiscard]] results — use std::ignore only when truly intentional
std::ignore = try_lock(); // document the deliberate discardA span carries a length with the pointer. Use checked access where an index comes from outside the valid range assumptions.