Official agent skill

Modern C++ Idioms

by trailofbits in trailofbits/skills

Steers C++ code toward C++20, C++23 and C++26 idioms such as smart pointers, concepts, std::expected and std::print, with a security focus.

OfficialCC-BY-SA-4.0Auto-check passedDevelopment

Install Modern C++ Idioms

skills CLI
$ npx skills add trailofbits/skills --skill modern-cpp -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install trailofbits/skills modern-cpp --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/trailofbits/skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/plugins/modern-cpp/skills/modern-cpp .claude/skills/modern-cpp && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
modern-cpp
GitHub stars
7.4k
Token cost
~2.2k tokens
SKILL.md length
767 words
Files
7 (incl. references)
Skills in repo
79
Repo updated
First seen
Licence
CC-BY-SA-4.0

At a glance

Steers C++ code toward C++20, C++23 and C++26 idioms such as smart pointers, concepts, std::expected and std::print, with a security focus.

  • Writing new C++ functions, classes or libraries to current standards
  • SKILL.md covers When to Use This Skill, When NOT to Use This Skill, Anti-Patterns to Avoid and Decision Tree, plus 5 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md
  • Modernizing code written to pre-C++20 patterns

What it does

This skill guides the agent when writing new C++ or modernizing older code, with an emphasis on patterns that remove whole classes of vulnerabilities. Its core is a table of what to avoid and what to use instead: new and delete give way to make_unique, C arrays to std::array, pointer plus length to std::span, printf to std::format or std::print, SFINAE to concepts, error codes to std::expected, and manual locking to std::scoped_lock.

Features are ranked into tiers by how usable they are today rather than by standard version, and a decision tree helps choose an approach. Reference files cover anti-patterns (30+ of them), compiler hardening, safe idioms and notes on the C++20, C++23 and C++26 features. The skill steps aside for pure C, build-system questions such as CMake, and projects that must stay on an older standard.

When your agent uses it

  • Writing new C++ functions, classes or libraries to current standards
  • Modernizing code written to pre-C++20 patterns
  • Working on security-critical or safety-sensitive C++
  • Reviewing C++ code for outdated idioms

Example prompts

  • “Rewrite this class to use std::unique_ptr and std::span instead of raw pointers and lengths.”
  • “Replace the printf calls in logger.cpp with std::print.”
  • “Review src/parser for places where concepts should replace enable_if.”

What it can do on your machine

Read from SKILL.md and the folder at commit 82fe822. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md.

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Modern C++ Idioms loads about 2.2k tokens when it runs, and up to ~13k if it reads all its reference files. Until then it costs about 70 tokens; SKILL.md has 767 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~70
When it runs · the whole SKILL.md, loaded when a task matches
~2.2k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~13k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from trailofbits/skills at commit 82fe822, republished under its CC-BY-SA-4.0 licence (© trailofbits). 767 words, ~2,158 tokens.

Download SKILL.mdSave it as .claude/skills/modern-cpp/SKILL.md (or your agent's skills folder). This skill also uses 6 other files; get the full folder from GitHub.
name
modern-cpp
description
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.

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.

Show full SKILL.md (285 more words)Show less

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

© trailofbits, CC-BY-SA-4.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 6 other files (references) in plugins/modern-cpp/skills/modern-cpp of trailofbits/skills.

  • SKILL.md
  • references/anti-patterns.md
  • references/compiler-hardening.md
  • references/cpp20-features.md
  • references/cpp23-features.md
  • references/cpp26-features.md
  • references/safe-idioms.md

Open the folder on GitHubat commit 82fe822

Compare with similar skills

Modern C++ Idioms next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Modern C++ Idioms compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Modern C++ Idioms this skilltrailofbits/skills7.4k—~2.2kAutomated safety check: PassCC-BY-SA-4.0
Code Refactoring Workflowluongnv89/claude-howto42k—~3.1kAutomated safety check: PassMIT
ONNX Runtime Shape Inference Safety Auditmicrosoft/onnxruntime22k—~3.3kAutomated safety check: PassMIT
Qt C++ Code Reviewx-tools-author/x-tools1.1k2 repos~4.3kAutomated safety check: PassBSD-3-Clause
Ripwire Output Emissionredhat-et/ripwire2.4k—~1kAutomated safety check: PassApache-2.0
Msbuild Antipatternsrunceel/ReactiveProperty944—~3.7kAutomated safety check: PassMIT

Similar skills

  • Code Refactoring Workflow

    luongnv89/claude-howto

    Guides systematic, test-backed refactoring in the style of Martin Fowler, moving through research, planning and small incremental changes with your approval at each phase.

    42k GitHub stars~3.1k tokensUpdated 7 days ago
    DevelopmentAuto-check passed
  • Official

    Finds and fixes out-of-range output writes in ONNX Runtime operator shape-inference functions where a getNumOutputs guard admits too few outputs.

    22k GitHub stars~3.3k tokensUpdated today
    SecurityAuto-check passed
  • Qt C++ Code Review

    x-tools-author/x-tools

    Read-only review of Qt6 C++ code that combines a deterministic lint script with six parallel analysis agents and reports only high-confidence issues.

    1.1k GitHub starsUsed in 2 repos~4.3k tokens
    DevelopmentAuto-check passed
  • Ripwire Output Emission

    redhat-et/ripwire

    Rules for writing and converting formatted output in ripwire's C++ source with its emit helpers, keeping every printed byte identical to the old printf output.

    2.4k GitHub stars~1k tokensUpdated 2 days ago
    DevelopmentAuto-check passed
  • Msbuild Antipatterns

    runceel/ReactiveProperty

    Catalog of MSBuild anti-patterns with detection rules and fix recipes.

    944 GitHub stars~3.7k tokensUpdated 1 mo ago
    DevelopmentAuto-check passed
  • WebRTC Include Cleaner

    webrtc-sdk/webrtc

    Runs the WebRTC include-cleaner tool to add missing and remove unused C++ include directives before uploading a CL or after refactoring.

    446 GitHub starsUsed in 1 repo~545 tokens
    DevelopmentAuto-check passed

More from trailofbits/skills

All 79 skills in this repo
  • CodeQL Security Scan

    trailofbits/skills

    Official

    Scans a codebase for vulnerabilities with CodeQL's data flow and taint tracking in run-all or important-only modes, including data extensions for project-specific sources and sinks.

    7.4k GitHub stars~4.6k tokensUpdated 5 days ago
    Auto-check: notes
  • Code Graph Mermaid Diagrams

    trailofbits/skills

    Official

    Generates Mermaid diagrams from Trailmark code graphs, including call graphs, class hierarchies, module dependency maps, complexity heatmaps and attack surface data flows.

    7.4k GitHub stars~1.7k tokensUpdated 5 days ago
    Auto-check passed
  • Trailmark Graph Evolution

    trailofbits/skills

    Official

    Compares Trailmark code graphs at two snapshots, such as commits, tags or directories, to surface attack paths, blast radius and taint changes that text diffs miss.

    7.4k GitHub stars~3.4k tokensUpdated 5 days ago
    Auto-check passed
  • Let Fate Decide

    trailofbits/skills

    Official

    Draws a 12 Houses tarot spread to break ties when a request is vague or casually delegated, then reads the cards to pick the next step.

    7.4k GitHub stars~2.5k tokensUpdated 5 days ago
    Auto-check: notes
  • Semgrep Security Scan

    trailofbits/skills

    Official

    Detects languages, proposes rulesets for approval, then runs the approved Semgrep scan across a codebase and merges the output into one SARIF file.

    7.4k GitHub stars~3.7k tokensUpdated 5 days ago
    Auto-check: notes
  • Burp Suite Project Parser

    trailofbits/skills

    Official

    Searches and extracts data from Burp Suite project files on the command line: regex searches over responses, audit findings, proxy history and site map data.

    7.4k GitHub starsUsed in 3 repos~4.2k tokens
    Auto-check: notes

Works with

Questions about Modern C++ Idioms

What does Modern C++ Idioms do?

Steers C++ code toward C++20, C++23 and C++26 idioms such as smart pointers, concepts, std::expected and std::print, with a security focus. This skill guides the agent when writing new C++ or modernizing older code, with an emphasis on patterns that remove whole classes of vulnerabilities. Its core is a table of what to avoid and what to use instead: new and delete give way to make_unique, C arrays to std::array, pointer plus length to std::span, printf to std::format or std::print, SFINAE to concepts, error codes to std::expected, and manual locking to std::scoped_lock.

When should I use Modern C++ Idioms?

Modern C++ Idioms fits situations like: writing new C++ functions, classes or libraries to current standards; modernizing code written to pre-C++20 patterns; working on security-critical or safety-sensitive C++; reviewing C++ code for outdated idioms.

How do I install Modern C++ Idioms in Claude Code?

Run `npx skills add trailofbits/skills --skill modern-cpp -a claude-code`. Or copy the skill folder (plugins/modern-cpp/skills/modern-cpp in trailofbits/skills) into .claude/skills/modern-cpp in your project. Claude Code loads it when a task matches its description.

How do I install Modern C++ Idioms in Codex?

Run `npx skills add trailofbits/skills --skill modern-cpp -a codex`. Or copy the skill folder (plugins/modern-cpp/skills/modern-cpp in trailofbits/skills) into .agents/skills/modern-cpp in your project. Codex loads it when a task matches its description.

Can I use Modern C++ Idioms in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add trailofbits/skills --skill modern-cpp -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/modern-cpp, .gemini/skills/modern-cpp, .github/skills/modern-cpp and .opencode/skills/modern-cpp in your project.

What does Modern C++ Idioms need to run?

SKILL.md names no scripts, command-line tools or credentials: Modern C++ Idioms is instructions for the agent only.

Does Modern C++ Idioms access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Modern C++ Idioms safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Modern C++ Idioms use?

Modern C++ Idioms is published under the CC-BY-SA-4.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Modern C++ Idioms use?

About 2.2k tokens (SKILL.md is roughly 8.6k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 11k tokens, read only when the agent opens those files.

What are the alternatives to Modern C++ Idioms?

Skills that share tags, products or a category with Modern C++ Idioms: Code Refactoring Workflow (luongnv89/claude-howto, 42k stars), ONNX Runtime Shape Inference Safety Audit (microsoft/onnxruntime, 22k stars), Qt C++ Code Review (x-tools-author/x-tools, 1.1k stars) and Ripwire Output Emission (redhat-et/ripwire, 2.4k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Modern C++ Idioms?

trailofbits (a GitHub organization, an official publisher) maintains it in trailofbits/skills, which has 7,400 GitHub stars. The repository holds 79 skills in this directory. The repository was last updated on October 2, 2026.

Source: trailofbits/skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.