Generated banner for Modern Cpp
Generated logo for Modern Cpp

Modern Cpp

Trail of BitsOfficialPublished by Trail of Bits

  • Skill
  • Guidelines
  • Software development
  • CC-BY-SA-4.0
  • No issues found

From the author

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.
— the description by Trail of Bits

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a comprehensive framework for transitioning C++ codebases toward modern standards. It emphasizes patterns that eliminate common vulnerability classes, such as memory leaks and buffer overflows, by replacing legacy C-style constructs with modern, type-safe alternatives. The content includes migration tables for anti-patterns, compiler hardening configurations, and feature tiers based on practical usability.

What it does

  • Provides migration paths from legacy C++ patterns to modern C++20/23/26 idioms.
  • Lists specific anti-patterns and their safer, modern replacements.
  • Details compiler hardening flags for GCC and Clang to improve security.
  • Explains the use of hardened libc++ modes for bounds-checking.
  • Categorizes C++ features by their current practical deployment readiness.
  • Offers a checklist for adopting safe coding practices in new and existing projects.

When to use it

  • When writing new C++ functions, classes, or libraries.
  • When modernizing legacy C++ codebases to improve safety and maintainability.
  • When working on security-critical or safety-sensitive C++ applications.
  • When reviewing C++ code to ensure adoption of modern idioms.
  • When configuring compiler and linker settings for enhanced security.

Advantages

  • Reduces vulnerability classes like memory leaks and buffer overflows.
  • Improves code readability and reduces boilerplate through modern language features.
  • Provides actionable, security-focused compiler and linker configurations.
  • Offers clear, evidence-based guidance on replacing legacy C-style constructs.
  • Helps align code with current C++ standards for better long-term maintainability.

Usage examples

“How should I replace raw pointers in my C++ code?”
The skill recommends using std::unique_ptr for exclusive ownership or std::shared_ptr for shared ownership to ensure RAII semantics and eliminate manual memory management.
“What are the recommended compiler flags for hardening a C++ project?”
The skill provides a list of essential flags including -D_FORTIFY_SOURCE=3, -fstack-protector-strong, and -ftrivial-auto-var-init=zero, along with linker settings like -Wl,-z,relro,-z,now.
“How can I replace printf in C++23?”
The skill suggests using std::print or std::println, which are type-safe and avoid the format string vulnerabilities associated with printf.
“What is the modern alternative to SFINAE?”
The skill advises using C++20 Concepts and the requires clause to constrain templates, which provides more readable code and clearer error messages.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/trailofbits/modern-cpp/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip modern-cpp.zip -d .agents/skills

Documentation by Trail of Bits

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

AvoidUse InsteadWhy
new/deletestd::make_unique, std::make_sharedEliminates leaks, double-free
Raw owning pointersstd::unique_ptr, std::shared_ptrRAII ownership semantics
C arrays (int arr[N])std::array<int, N>Bounds-aware, value semantics
Pointer + length paramsstd::span<T>Non-owning, bounds-checkable
printf / sprintfstd::format, std::printType-safe, no buffer overflow
C-style casts (int)xstatic_cast<int>(x)Explicit intent, auditable
#define constantsconstexpr variablesScoped, typed, debuggable
SFINAE / enable_ifConcepts + requiresReadable constraints and errors
Error codes + out paramsstd::expected<T, E>Composable, type-safe errors
unionstd::variantType-safe, no silent UB
Raw mutex.lock()/unlock()std::scoped_lockException-safe, no deadlocks
std::threadstd::jthreadAuto-join, stop token support
assert() macrocontract_assert (C++26)Visible to tooling, configurable
Manual CRTPDeducing this (C++23)Simpler, no template boilerplate
Macro code generationReflection (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)
FeatureReplacesStandard
Concepts + requiresSFINAE, enable_ifC++20
Ranges + viewsRaw iterator loopsC++20
std::span<T>Pointer + lengthC++20
std::formatsprintf, iostream chainsC++20
Three-way comparison <=>Manual comparison operatorsC++20
std::jthreadstd::thread + manual joinC++20
Designated initializersPositional struct initC++20
std::expected<T,E>Error codes, exceptions at boundariesC++23
std::print / std::printlnprintf, std::cout <<C++23
Deducing thisCRTP, const/non-const duplicationC++23
std::flat_mapstd::map for read-heavy useC++23
Monadic std::optionalNested if-checks on optionalsC++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

RationalizationWhy 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

  • [ ] Use smart pointers for ownership, raw pointers only for non-owning observation

  • [ ] Prefer std::span over pointer + length for function parameters

  • [ ] Use std::expected for functions that can fail with typed errors

  • [ ] Constrain templates with concepts, not SFINAE

  • [ ] Enable compiler hardening flags and hardened libc++ in all builds

  • [ ] Run ASan + UBSan in CI; add TSan for concurrent code

  • [ ] Use constexpr / consteval where possible (UB-free by design)

  • [ ] Mark functions [[nodiscard]] when ignoring the return value is likely a bug

  • [ ] Prefer value semantics; use std::variant over union, enum class over enum

  • [ ] Initialize all variables at declaration

Files

references/cpp26-features.md

C++26 Features

C++26 was finalized in March 2026 — the most significant release since C++11. This reference covers the features worth knowing about, ranked by practical impact.

Reflection (Game-Changer)

Static reflection is the single most impactful C++26 feature. It lets programs inspect types, members, and functions at compile time and generate code with zero runtime overhead.

What It Eliminates
  • Per-struct serialization functions (JSON, protobuf, XML)

  • Code generators (protobuf codegen, Qt MOC, flatbuffers)

  • Macro-based registration systems (enum-to-string, type registries)

  • Verbose template metaprogramming with std::tuple tricks

Core Syntax

The ^^ operator ("reflection operator") reflects a construct into a std::meta::info value:

#include <meta>

constexpr auto type_info = ^^int;  // reflect the type 'int'
constexpr auto member_info = ^^MyStruct::field;  // reflect a member

Key std::meta:: functions:

  • nonstatic_data_members_of(^^T) — enumerate struct members

  • identifier_of(member) — get member name as string

  • type_of(member) — get member type

  • enumerators_of(^^E) — enumerate enum values

The splice operator [:expr:] converts a reflection back into code.

Before / After
// BEFORE: write this for EVERY struct, update when fields change
json to_json(const Player& p) {
    return {{"name", p.name}, {"health", p.health},
            {"x", p.x}, {"y", p.y}, {"score", p.score}};
}

// AFTER: one function, works for ANY struct, never needs updating
template <typename T>
json to_json(const T& obj) {
    json result;
    template for (constexpr auto member :
                  std::meta::nonstatic_data_members_of(^^T)) {
        result[std::meta::identifier_of(member)] = obj.[:member:];
    }
    return result;
}
Enum-to-String (Classic Pain Point)
// BEFORE: manual mapping, breaks when you add values
const char* to_string(Color c) {
    switch (c) {
        case Color::Red: return "Red";
        case Color::Green: return "Green";
        case Color::Blue: return "Blue";
    }
}

// AFTER: works for any enum, automatically
template <typename E>
    requires std::is_enum_v<E>
std::string to_string(E value) {
    template for (constexpr auto e : std::meta::enumerators_of(^^E)) {
        if (value == [:e:])
            return std::string(std::meta::identifier_of(e));
    }
    return "<unknown>";
}
Compiler Support
When to Use / Not Use
  • Use for: Serialization, deserialization, ORM mapping, debug printing, enum conversion, logging, plugin systems

  • Don't use for: Simple code where templates or concepts suffice; reflection adds compile-time complexity

Contracts

Language-level preconditions, postconditions, and assertions.

Syntax
// Precondition — checked before function body executes
void transfer(Account& from, Account& to, int amount)
    pre (amount > 0)
    pre (from.balance >= amount)
    post (from.balance >= 0)
{
    from.balance -= amount;
    to.balance += amount;
}

// In-body assertion
void process(std::span<int> data) {
    contract_assert(!data.empty());
    // ...
}
Enforcement Modes
ModeBehavior
enforceCheck, call violation handler, terminate if it returns
observeCheck, call violation handler, continue execution
ignoreSkip the check entirely
quick_enforceCheck, terminate immediately (no handler)

Mode is selected at build time, not per-contract.

Before / After
// BEFORE: preconditions buried in body, invisible to callers
int divide(int a, int b) {
    assert(b != 0);  // only in debug builds, invisible to IDE
    return a / b;
}

// AFTER: preconditions on declaration, visible to callers and tools
int divide(int a, int b)
    pre (b != 0);
Honest Limitations
  • No virtual function contracts — deferred to a future standard

  • Controversial design — Bjarne Stroustrup has publicly criticized the design

  • Compiler support is experimental — GCC trunk has it, not production-ready

  • Side effects in contract expressions are unspecified

Recommendation

Adopt cautiously. Use for new API boundaries where preconditions should be visible. Don't rewrite existing assert() usage wholesale until compilers mature.

Memory Safety Improvements

Erroneous Behavior for Uninitialized Reads

Uninitialized local variable reads are no longer undefined behavior. They become "erroneous behavior" — well-defined (the variable holds a valid but unspecified value) but diagnosable.

Practical impact: Compilers can no longer use "this read is UB, so I can optimize away your null check" reasoning. Just recompiling as C++26 gives you this protection.

Opt-out: [[indeterminate]] attribute for performance-critical code where you can prove the variable is written before read.

Hardened Standard Library

Bounds-checking preconditions added to operator[], front(), back(), etc. on std::vector, std::span, std::string, std::string_view, std::array, std::optional, std::expected.

Google's deployment results:

  • Deployed across Chrome and entire server fleet

  • ~0.3% average performance overhead

  • 1000+ previously undetected bugs found

  • 30% reduction in production segfault rate

Enable today (no need to wait for C++26):

-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST

See compiler-hardening.md for details.

Smaller Wins

#embed

Embed binary data at compile time without external tools:

// BEFORE: xxd -i data.bin > data.h (slow, 70+ seconds for 40MB)
static const unsigned char data[] = { 0x89, 0x50, 0x4E, ... };

// AFTER: instant, handled by compiler
static constexpr unsigned char data[] = {
    #embed "data.bin"
};

GCC 15+ and Clang 19+ support #embed.

std::inplace_vector<T, N>

Fixed-capacity, dynamically-resizable vector with no heap allocation. Replaces boost::static_vector.

std::inplace_vector<int, 64> small_buf;  // max 64 elements, stack-allocated
small_buf.push_back(42);  // works like vector
// small_buf.push_back() when full: throws (or use try_push_back for fallible API)
std::function_ref

Non-owning, non-allocating callable wrapper. The std::string_view of callables.

// BEFORE: std::function allocates, type-erases, is nullable
void for_each(std::span<int> data, std::function<void(int)> fn);

// AFTER: zero allocation, passable in registers
void for_each(std::span<int> data, std::function_ref<void(int)> fn);
std::indirect<T> and std::polymorphic<T>

Value-semantic wrappers for heap-allocated objects:

  • std::indirect<T> — like unique_ptr but copyable (deep copies)

  • std::polymorphic<T> — adds virtual dispatch with value semantics

Placeholder Variables
auto [x, _, _] = get_triple();     // ignore second and third
std::lock_guard _(mutex);          // unnamed RAII guard
for (auto _ : std::views::iota(0, 5)) { /* repeat 5 times */ }
Other Notable Additions
  • Pack indexing T...[N] — direct variadic pack access

  • Saturation arithmetic — std::add_sat, std::sub_sat, std::mul_sat

  • = delete("reason") — document why an overload is deleted

  • std::hive — bucket container with stable pointers and O(1) insert/erase

  • <simd> — data-parallel SIMD types

  • <linalg> — BLAS-based linear algebra

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Trail of Bits
Publisher
Trail of Bits (Official)
Source
trailofbits/skills · plugins/modern-cpp/skills/modern-cpp · commit e4dd0bb
Licence
Creative Commons Attribution-ShareAlike 4.0 International (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Trail of Bits or Trail of Bits.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download modern-cpp.zip