Modern C++
Guide for writing modern C++ using C++20, C++23, and C++26 idioms. Focuses on patterns that eliminate vulnerability classes and reduce boilerplate, with a security emphasis from Trail of Bits.
When to Use This Skill
- Writing new C++ functions, classes, or libraries
- Modernizing existing C++ code (pre-C++20 patterns)
- Choosing between legacy and modern approaches
- Working on security-critical or safety-sensitive C++
- Reviewing C++ code for modern idiom adoption
When NOT to Use This Skill
- User explicitly requires older standard: Respect constraints (embedded, legacy ABI)
- Pure C code: This skill is C++-specific
- Build system questions: CMake, Meson, Bazel configuration is out of scope
- Non-C++ projects: Mixed codebases where C++ isn't primary
Anti-Patterns to Avoid
| Avoid |
Use Instead |
Why |
new/delete |
std::make_unique, std::make_shared |
Eliminates leaks, double-free |
| Raw owning pointers |
std::unique_ptr, std::shared_ptr |
RAII ownership semantics |
C arrays (int arr[N]) |
std::array<int, N> |
Bounds-aware, value semantics |
| Pointer + length params |
std::span<T> |
Non-owning, bounds-checkable |
printf / sprintf |
std::format, std::print |
Type-safe, no buffer overflow |
C-style casts (int)x |
static_cast<int>(x) |
Explicit intent, auditable |
#define constants |
constexpr variables |
Scoped, typed, debuggable |
SFINAE / enable_if |
Concepts + requires |
Readable constraints and errors |
| Error codes + out params |
std::expected<T, E> |
Composable, type-safe errors |
union |
std::variant |
Type-safe, no silent UB |
Raw mutex.lock()/unlock() |
std::scoped_lock |
Exception-safe, no deadlocks |
std::thread |
std::jthread |
Auto-join, stop token support |
assert() macro |
contract_assert (C++26) |
Visible to tooling, configurable |
| Manual CRTP |
Deducing this (C++23) |
Simpler, no template boilerplate |
| Macro code generation |
Reflection (C++26) |
Zero-overhead, composable |
See anti-patterns.md for the full table (30+ patterns).
Decision Tree
What are you doing?
|
+-- Writing new C++ code?
| +-- Use modern idioms by default (C++20/23)
| +-- Choose the newest standard your compiler supports
| +-- See Feature Tiers below
|
+-- Modernizing existing code?
| +-- Start with Tier 1 (C++20/23) replacements
| +-- Prioritize by security impact (memory > types > style)
| +-- See anti-patterns.md for the migration table
|
+-- Security-critical code?
| +-- Enable compiler hardening flags (see below)
| +-- Enable hardened libc++ mode
| +-- Run sanitizers in CI
| +-- See safe-idioms.md and compiler-hardening.md
|
+-- Using C++26 features?
+-- Reflection: YES, plan for it (GCC 16+)
+-- Contracts: cautiously, for new API boundaries
+-- std::execution: wait for ecosystem maturity
+-- See cpp26-features.md
Feature Tiers
Features are ranked by practical usability today, not by standard version.
Tier 1: Use Today (C++20/23, solid compiler support)
| Feature |
Replaces |
Standard |
Concepts + requires |
SFINAE, enable_if |
C++20 |
| Ranges + views |
Raw iterator loops |
C++20 |
std::span<T> |
Pointer + length |
C++20 |
std::format |
sprintf, iostream chains |
C++20 |
Three-way comparison <=> |
Manual comparison operators |
C++20 |
std::jthread |
std::thread + manual join |
C++20 |
| Designated initializers |
Positional struct init |
C++20 |
std::expected<T,E> |
Error codes, exceptions at boundaries |
C++23 |
std::print / std::println |
printf, std::cout << |
C++23 |
Deducing this |
CRTP, const/non-const duplication |
C++23 |
std::flat_map |
std::map for read-heavy use |
C++23 |
Monadic std::optional |
Nested if-checks on optionals |
C++23 |
See cpp20-features.md and cpp23-features.md.
Tier 2: Deploy Now (no standard bump needed)
These improve safety without changing your C++ standard version:
- Compiler hardening flags —
-D_FORTIFY_SOURCE=3, -fstack-protector-strong, -ftrivial-auto-var-init=zero
- Hardened libc++ —
-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST for ~0.3% overhead bounds-checking
- Sanitizers in CI — ASan + UBSan as minimum; TSan for concurrent code
- Warning flags —
-Wall -Wextra -Wpedantic -Werror
See compiler-hardening.md.
Tier 3: Plan For (C++26, worth restructuring around)
Reflection is the single most transformative C++26 feature. It eliminates:
- Serialization boilerplate (one generic function replaces per-struct
to_json)
- Code generators (protobuf codegen, Qt MOC)
- Macro-based registration and enum-to-string hacks
GCC 16 (April 2026) has reflection merged. Plan new code to benefit from it.
Tier 4: Watch (C++26, needs maturation)
- Contracts (
pre/post/contract_assert) — Better than assert(), but no virtual function support and limited compiler support. Adopt cautiously for new API boundaries.
- std::execution (senders/receivers) — Powerful async framework, but steep learning curve, no scheduler ships with it, and poor documentation. Wait for ecosystem maturity.
See cpp26-features.md.
Compiler Hardening Quick Reference
Essential Flags (GCC + Clang)
-Wall -Wextra -Wpedantic -Werror
-D_FORTIFY_SOURCE=3
-fstack-protector-strong
-fstack-clash-protection
-ftrivial-auto-var-init=zero
-fPIE -pie
-Wl,-z,relro,-z,now
Clang-Specific
-Wunsafe-buffer-usage
Hardened libc++ (Clang/libc++ only)
-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST
Google deployed this across Chrome and their server fleet: ~0.3% overhead, 1000+ bugs found, 30% reduction in production segfaults.
See compiler-hardening.md for the full guide.
Rationalizations to Reject
| Rationalization |
Why It's Wrong |
| "It compiles without warnings" |
Warnings depend on which flags you enable. Add -Wall -Wextra -Wpedantic. |
| "ASan is too slow for production" |
Use GWP-ASan for sampling-based production detection (~0% overhead). |
| "We only use safe containers" |
Iterator invalidation and unchecked optional access are still exploitable. |
| "Smart pointers are slower" |
std::unique_ptr has zero overhead vs raw pointers. Measure before claiming. |
| "Our code doesn't have memory bugs" |
Google found 1000+ bugs when enabling hardened libc++. So did everyone else. |
| "C++26 features aren't available yet" |
C++20/23 features are. Hardening flags work on any standard. Start there. |
| "Modern C++ is harder to read" |
std::expected is more readable than checking error codes across 5 out-params. |
Best Practices Checklist
Read Next
- anti-patterns.md — Full legacy-to-modern migration table (30+ patterns)
- cpp20-features.md — Concepts, ranges, span, format, coroutines
- cpp23-features.md — expected, print, deducing this, flat_map
- cpp26-features.md — Reflection, contracts, memory safety improvements
- compiler-hardening.md — Flags, sanitizers, hardened libc++
- safe-idioms.md — Security patterns by vulnerability class
1---2name: modern-cpp3description: Guides C++ code toward modern idioms (C++20/23/26). Use when writing new C++ code, modernizing legacy patterns, or working on security-critical C++. Replaces raw pointers with smart pointers, SFINAE with concepts, printf with std::print, error codes with std::expected.4metadata:5 source: https://skillmd.com/skills/trailofbits/modern-cpp6---78# Modern C++910Guide for writing modern C++ using C++20, C++23, and C++26 idioms. Focuses on patterns that eliminate vulnerability classes and reduce boilerplate, with a security emphasis from Trail of Bits.1112## When to Use This Skill1314- Writing new C++ functions, classes, or libraries15- Modernizing existing C++ code (pre-C++20 patterns)16- Choosing between legacy and modern approaches17- Working on security-critical or safety-sensitive C++18- Reviewing C++ code for modern idiom adoption1920## When NOT to Use This Skill2122- **User explicitly requires older standard**: Respect constraints (embedded, legacy ABI)23- **Pure C code**: This skill is C++-specific24- **Build system questions**: CMake, Meson, Bazel configuration is out of scope25- **Non-C++ projects**: Mixed codebases where C++ isn't primary2627## Anti-Patterns to Avoid2829| Avoid | Use Instead | Why |30|-------|-------------|-----|31| `new`/`delete` | `std::make_unique`, `std::make_shared` | Eliminates leaks, double-free |32| Raw owning pointers | `std::unique_ptr`, `std::shared_ptr` | RAII ownership semantics |33| C arrays (`int arr[N]`) | `std::array<int, N>` | Bounds-aware, value semantics |34| Pointer + length params | `std::span<T>` | Non-owning, bounds-checkable |35| `printf` / `sprintf` | `std::format`, `std::print` | Type-safe, no buffer overflow |36| C-style casts `(int)x` | `static_cast<int>(x)` | Explicit intent, auditable |37| `#define` constants | `constexpr` variables | Scoped, typed, debuggable |38| SFINAE / `enable_if` | Concepts + `requires` | Readable constraints and errors |39| Error codes + out params | `std::expected<T, E>` | Composable, type-safe errors |40| `union` | `std::variant` | Type-safe, no silent UB |41| Raw `mutex.lock()/unlock()` | `std::scoped_lock` | Exception-safe, no deadlocks |42| `std::thread` | `std::jthread` | Auto-join, stop token support |43| `assert()` macro | `contract_assert` (C++26) | Visible to tooling, configurable |44| Manual CRTP | Deducing `this` (C++23) | Simpler, no template boilerplate |45| Macro code generation | Reflection (C++26) | Zero-overhead, composable |4647See [anti-patterns.md](./references/anti-patterns.md) for the full table (30+ patterns).4849## Decision Tree5051```52What are you doing?53|54+-- Writing new C++ code?55| +-- Use modern idioms by default (C++20/23)56| +-- Choose the newest standard your compiler supports57| +-- See Feature Tiers below58|59+-- Modernizing existing code?60| +-- Start with Tier 1 (C++20/23) replacements61| +-- Prioritize by security impact (memory > types > style)62| +-- See anti-patterns.md for the migration table63|64+-- Security-critical code?65| +-- Enable compiler hardening flags (see below)66| +-- Enable hardened libc++ mode67| +-- Run sanitizers in CI68| +-- See safe-idioms.md and compiler-hardening.md69|70+-- Using C++26 features?71 +-- Reflection: YES, plan for it (GCC 16+)72 +-- Contracts: cautiously, for new API boundaries73 +-- std::execution: wait for ecosystem maturity74 +-- See cpp26-features.md75```7677## Feature Tiers7879Features are ranked by **practical usability today**, not by standard version.8081### Tier 1: Use Today (C++20/23, solid compiler support)8283| Feature | Replaces | Standard |84|---------|----------|----------|85| Concepts + `requires` | SFINAE, `enable_if` | C++20 |86| Ranges + views | Raw iterator loops | C++20 |87| `std::span<T>` | Pointer + length | C++20 |88| `std::format` | `sprintf`, iostream chains | C++20 |89| Three-way comparison `<=>` | Manual comparison operators | C++20 |90| `std::jthread` | `std::thread` + manual join | C++20 |91| Designated initializers | Positional struct init | C++20 |92| `std::expected<T,E>` | Error codes, exceptions at boundaries | C++23 |93| `std::print` / `std::println` | `printf`, `std::cout <<` | C++23 |94| Deducing `this` | CRTP, const/non-const duplication | C++23 |95| `std::flat_map` | `std::map` for read-heavy use | C++23 |96| Monadic `std::optional` | Nested if-checks on optionals | C++23 |9798See [cpp20-features.md](./references/cpp20-features.md) and [cpp23-features.md](./references/cpp23-features.md).99100### Tier 2: Deploy Now (no standard bump needed)101102These improve safety without changing your C++ standard version:103104- **Compiler hardening flags** — `-D_FORTIFY_SOURCE=3`, `-fstack-protector-strong`, `-ftrivial-auto-var-init=zero`105- **Hardened libc++** — `-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST` for ~0.3% overhead bounds-checking106- **Sanitizers in CI** — ASan + UBSan as minimum; TSan for concurrent code107- **Warning flags** — `-Wall -Wextra -Wpedantic -Werror`108109See [compiler-hardening.md](./references/compiler-hardening.md).110111### Tier 3: Plan For (C++26, worth restructuring around)112113**Reflection** is the single most transformative C++26 feature. It eliminates:114- Serialization boilerplate (one generic function replaces per-struct `to_json`)115- Code generators (protobuf codegen, Qt MOC)116- Macro-based registration and enum-to-string hacks117118GCC 16 (April 2026) has reflection merged. Plan new code to benefit from it.119120### Tier 4: Watch (C++26, needs maturation)121122- **Contracts** (`pre`/`post`/`contract_assert`) — Better than `assert()`, but no virtual function support and limited compiler support. Adopt cautiously for new API boundaries.123- **std::execution** (senders/receivers) — Powerful async framework, but steep learning curve, no scheduler ships with it, and poor documentation. Wait for ecosystem maturity.124125See [cpp26-features.md](./references/cpp26-features.md).126127## Compiler Hardening Quick Reference128129### Essential Flags (GCC + Clang)130131```132-Wall -Wextra -Wpedantic -Werror133-D_FORTIFY_SOURCE=3134-fstack-protector-strong135-fstack-clash-protection136-ftrivial-auto-var-init=zero137-fPIE -pie138-Wl,-z,relro,-z,now139```140141### Clang-Specific142143```144-Wunsafe-buffer-usage145```146147### Hardened libc++ (Clang/libc++ only)148149```150-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST151```152153Google deployed this across Chrome and their server fleet: ~0.3% overhead, 1000+ bugs found, 30% reduction in production segfaults.154155See [compiler-hardening.md](./references/compiler-hardening.md) for the full guide.156157## Rationalizations to Reject158159| Rationalization | Why It's Wrong |160|----------------|----------------|161| "It compiles without warnings" | Warnings depend on which flags you enable. Add `-Wall -Wextra -Wpedantic`. |162| "ASan is too slow for production" | Use GWP-ASan for sampling-based production detection (~0% overhead). |163| "We only use safe containers" | Iterator invalidation and unchecked `optional` access are still exploitable. |164| "Smart pointers are slower" | `std::unique_ptr` has zero overhead vs raw pointers. Measure before claiming. |165| "Our code doesn't have memory bugs" | Google found 1000+ bugs when enabling hardened libc++. So did everyone else. |166| "C++26 features aren't available yet" | C++20/23 features are. Hardening flags work on any standard. Start there. |167| "Modern C++ is harder to read" | `std::expected` is more readable than checking error codes across 5 out-params. |168169## Best Practices Checklist170171- [ ] Use smart pointers for ownership, raw pointers only for non-owning observation172- [ ] Prefer `std::span` over pointer + length for function parameters173- [ ] Use `std::expected` for functions that can fail with typed errors174- [ ] Constrain templates with concepts, not SFINAE175- [ ] Enable compiler hardening flags and hardened libc++ in all builds176- [ ] Run ASan + UBSan in CI; add TSan for concurrent code177- [ ] Use `constexpr` / `consteval` where possible (UB-free by design)178- [ ] Mark functions `[[nodiscard]]` when ignoring the return value is likely a bug179- [ ] Prefer value semantics; use `std::variant` over `union`, `enum class` over `enum`180- [ ] Initialize all variables at declaration181182## Read Next183184- [anti-patterns.md](./references/anti-patterns.md) — Full legacy-to-modern migration table (30+ patterns)185- [cpp20-features.md](./references/cpp20-features.md) — Concepts, ranges, span, format, coroutines186- [cpp23-features.md](./references/cpp23-features.md) — expected, print, deducing this, flat_map187- [cpp26-features.md](./references/cpp26-features.md) — Reflection, contracts, memory safety improvements188- [compiler-hardening.md](./references/compiler-hardening.md) — Flags, sanitizers, hardened libc++189- [safe-idioms.md](./references/safe-idioms.md) — Security patterns by vulnerability class