Communitygithub.com

trailofbits/modern-cpp

C++コードをC++20/23/26のモダンなイディオムへ導きます。新しいC++コードの作成、レガシーパターンのモダナイズ、セキュリティ・クリティカルなC++の作業時に使用します。生ポインタをスマートポインタに、SFINAEをコンセプトに、printfをstd::printに、エラーコードをstd::expectedに置き換えます。

modern-cpp とは?

このスキルは、Trail of Bitsのセキュリティ重視のアプローチに基づき、C++コードをC++20、C++23、C++26のモダンなイディオムへ導くための包括的なガイドです。脆弱性クラスを排除し、ボイラープレートコードを削減することに焦点を当てており、新しいC++コードの作成、既存のレガシーコードのモダナイズ、セキュリティ・クリティカルなコードのレビューなど、さまざまなユースケースに対応します。スキルは、コンパイラのハードニングフラグや強化されたlibc++モードの設定、サニタイザーのCI統合など、実践的なセキュリティ対策もカバーしています。機能は実用的な使用可能性に基づいて4つのティア(今日すぐ使えるTier 1、標準バージョン変更不要のTier 2、計画すべきC++26機能のTier 3、成熟を待つべきTier 4)に分類されており、15以上のアンチパターンを具体的な対処法とともにマッピングした表も含まれます。このスキルはClaude Code、Cursor、CodexなどのAIエージェントで動作し、開発者がより安全で保守性の高いC++コードを効率的に記述できるよう支援します。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/trailofbits/skills/tree/main/plugins/modern-cpp/skills/modern-cpp

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Modern C++(モダンC++)

C++20、C++23、C++26のイディオムを使用したモダンC++記述のためのガイドです。脆弱性クラスを排除し、ボイラープレートを削減するパターンに焦点を当て、Trail of Bitsによるセキュリティ重視の内容となっています。

このスキルを使用するタイミング

  • 新しいC++関数、クラス、またはライブラリを作成する場合
  • 既存のC++コード(C++20以前のパターン)をモダナイズする場合
  • レガシーなアプローチとモダンなアプローチのどちらかを選択する場合
  • セキュリティ・クリティカルまたは安全性重視のC++を扱う場合
  • C++コードをモダンなイディオムの採用についてレビューする場合

このスキルを使用すべきでないタイミング

  • ユーザーが明示的に古い標準を要求している場合: 制約(組み込み、レガシーABI)を尊重します
  • 純粋なCコードの場合: このスキルはC++固有です
  • ビルドシステムに関する質問の場合: CMake、Meson、Bazelの設定は範囲外です
  • C++以外のプロジェクトの場合: C++が主要でない混在コードベース

回避すべきアンチパターン

避けるべき記述代わりに使用する記述理由
new/deletestd::make_unique、std::make_sharedメモリリーク、ダブルフリーを排除
生の所有ポインタstd::unique_ptr、std::shared_ptrRAIIによる所有権セマンティクス
C配列(int arr[N])std::array<int, N>境界認識、値セマンティクス
ポインタ+長さの引数std::span<T>非所有、境界チェック可能
printf / sprintfstd::format、std::print型安全、バッファオーバーフローなし
Cスタイルキャスト (int)xstatic_cast<int>(x)意図が明確、監査可能
#define 定数constexpr 変数スコープ付き、型付き、デバッグ可能
SFINAE / enable_ifコンセプト + requires読みやすい制約とエラーメッセージ
エラーコード + 出力引数std::expected<T, E>合成可能、型安全なエラー
unionstd::variant型安全、暗黙の未定義動作なし
生の mutex.lock()/unlock()std::scoped_lock例外安全、デッドロックなし
std::threadstd::jthread自動ジョイン、停止トークンサポート
assert() マクロcontract_assert(C++26)ツールから可視、設定可能
手動CRTPDeducing this(C++23)よりシンプル、テンプレートのボイラープレート不要
マクロによるコード生成リフレクション(C++26)ゼロオーバーヘッド、合成可能

完全なテーブル(30以上のパターン)については anti-patterns.md を参照してください。

決定木

何をしていますか?
|
+-- 新しいC++コードを書いていますか?
|   +-- デフォルトでモダンなイディオム(C++20/23)を使用
|   +-- コンパイラがサポートする最新の標準を選択
|   +-- 以下の機能ティアを参照
|
+-- 既存コードをモダナイズしていますか?
|   +-- Tier 1(C++20/23)の置き換えから開始
|   +-- セキュリティへの影響で優先順位付け(メモリ > 型 > スタイル)
|   +-- 移行テーブルについては anti-patterns.md を参照
|
+-- セキュリティ・クリティカルなコードですか?
|   +-- コンパイラのハードニングフラグを有効化(以下を参照)
|   +-- 強化されたlibc++モードを有効化
|   +-- CIでサニタイザーを実行
|   +-- safe-idioms.md と compiler-hardening.md を参照
|
+-- C++26の機能を使用していますか?
    +-- リフレクション: はい、計画を立ててください(GCC 16+)
    +-- Contracts: 新しいAPI境界では慎重に
    +-- std::execution: エコシステムの成熟を待つ
    +-- cpp26-features.md を参照

機能ティア

機能は標準バージョンではなく、今日の実用的な使用可能性に基づいてランク付けされています。

Tier 1: 今日すぐ使える(C++20/23、堅牢なコンパイラサポート)

機能置き換え対象標準
コンセプト + requiresSFINAE、enable_ifC++20
Ranges + views生のイテレータループC++20
std::span<T>ポインタ+長さC++20
std::formatsprintf、iostreamチェーンC++20
三方比較 <=>手動比較演算子C++20
std::jthreadstd::thread + 手動ジョインC++20
指示付き初期化子位置指定構造体初期化C++20
std::expected<T,E>エラーコード、境界での例外C++23
std::print / std::printlnprintf、std::cout <<C++23
Deducing thisCRTP、const/non-constの重複C++23
std::flat_map読み取り重視のstd::mapC++23
モナディックstd::optionaloptionalに対するネストされたifチェックC++23

cpp20-features.md と cpp23-features.md を参照してください。

Tier 2: 今すぐデプロイ可能(標準バージョンの変更不要)

これらはC++標準バージョンを変更せずに安全性を向上させます:

  • コンパイラハードニングフラグ — -D_FORTIFY_SOURCE=3、-fstack-protector-strong、-ftrivial-auto-var-init=zero
  • 強化されたlibc++ — -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST、約0.3%のオーバーヘッドで境界チェック
  • CIでのサニタイザー — 最低限ASan + UBSan、並行コードにはTSan
  • 警告フラグ — -Wall -Wextra -Wpedantic -Werror

compiler-hardening.md を参照してください。

Tier 3: 計画を立てる(C++26、再構成に値する)

リフレクションは、C++26の最も変革的な機能です。以下を排除します:

  • シリアライゼーションのボイラープレート(構造体ごとの to_json を1つのジェネリック関数で置き換え)
  • コードジェネレーター(protobuf codegen、Qt MOC)
  • マクロベースの登録と enum-to-string ハック

GCC 16(2026年4月)はリフレクションをマージ済みです。新しいコードが恩恵を受けられるよう計画してください。

Tier 4: 様子を見る(C++26、成熟が必要)

  • Contracts(pre/post/contract_assert) — assert() より優れていますが、仮想関数のサポートがなく、コンパイラのサポートも限定的です。新しいAPI境界では慎重に採用してください。
  • std::execution(senders/receivers) — 強力な非同期フレームワークですが、学習曲線が急で、スケジューラーが同梱されておらず、ドキュメントも不十分です。エコシステムの成熟を待ってください。

cpp26-features.md を参照してください。

コンパイラハードニングクイックリファレンス

必須フラグ(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固有

-Wunsafe-buffer-usage

強化されたlibc++(Clang/libc++のみ)

-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST

GoogleはこれをChromeとサーバーフリート全体に展開しました:約0.3%のオーバーヘッド、1000以上のバグを発見、本番セグメンテーションフォールトを30%削減。

完全なガイドについては compiler-hardening.md を参照してください。

却下すべき合理化

合理化なぜ間違っているか
「警告なしでコンパイルできる」警告は有効にするフラグに依存します。-Wall -Wextra -Wpedantic を追加してください。
「ASanは本番環境で遅すぎる」GWP-ASanをサンプリングベースの本番検出(約0%オーバーヘッド)に使用してください。
「安全なコンテナだけを使っている」イテレータの無効化やチェックされていない optional アクセスは依然として悪用可能です。
「スマートポインタは遅い」std::unique_ptr は生ポインタと比較してゼロオーバーヘッドです。主張する前に計測してください。
「私たちのコードにはメモリバグがない」Googleは強化されたlibc++を有効にした際に1000以上のバグを発見しました。他のすべての組織も同様です。
「C++26の機能はまだ利用できない」C++20/23の機能は利用可能です。ハードニングフラグはどの標準でも動作します。そこから始めてください。
「モダンC++は読みにくい」std::expected は5つの出力引数にわたってエラーコードをチェックするよりも読みやすいです。

ベストプラクティスチェックリスト

  • 所有権にはスマートポインタを使用し、生ポインタは非所有の監視のみに使用する
  • 関数パラメータにはポインタ+長さよりも std::span を優先する
  • 型付きエラーで失敗する可能性のある関数には std::expected を使用する
  • テンプレートはSFINAEではなくコンセプトで制約する
  • すべてのビルドでコンパイラハードニングフラグと強化されたlibc++を有効にする
  • CIでASan + UBSanを実行し、並行コードにはTSanを追加する
  • 可能な場合は constexpr / consteval を使用する(設計上未定義動作なし)
  • 戻り値を無視することがバグである可能性がある場合は、関数に [[nodiscard]] を付ける
  • 値セマンティクスを優先し、union の代わりに std::variant、enum の代わりに enum class を使用する
  • すべての変数を宣言時に初期化する

次に読むもの

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

trailofbits/address-sanitizer

AddressSanitizer detects memory errors during fuzzing. Use when fuzzing C/C++ code to find buffer overflows and use-after-free bugs.

trailofbits/aflpp

AFL++ is a fork of AFL with better fuzzing performance and advanced features. Use for multi-core fuzzing of C/C++ projects.

trailofbits/agentic-actions-auditor

Audits GitHub Actions workflows for security vulnerabilities in AI agent integrations including Claude Code Action, Gemini CLI, OpenAI Codex, and GitHub AI Inference. Detects attack vectors where attacker-controlled input reaches AI agents running in CI/CD pipelines, including env var intermediary patterns, direct expression injection, dangerous sandbox configurations, and wildcard user allowlists. Use when reviewing workflow files that invoke AI coding agents, auditing CI/CD pipeline security for prompt injection risks, or evaluating agentic action configurations.

trailofbits/algorand-vulnerability-scanner

Scans Algorand smart contracts for 11 common vulnerabilities including rekeying attacks, unchecked transaction fees, missing field validations, and access control issues. Use when auditing Algorand projects (TEAL/PyTeal).

trailofbits/ask-questions-if-underspecified

Clarify requirements before implementing. Use when serious doubts arise.

trailofbits/atheris

Atheris is a coverage-guided Python fuzzer based on libFuzzer. Use for fuzzing pure Python code and Python C extensions.

trailofbits/audit-augmentation

Augments Trailmark code graphs with external audit findings from SARIF static analysis results and weAudit annotation files. Maps findings to graph nodes by file and line overlap, creates severity-based subgraphs, and enables cross-referencing findings with pre-analysis data (blast radius, taint, etc.). Use when projecting SARIF results onto a code graph, overlaying weAudit annotations, cross-referencing Semgrep or CodeQL findings with call graph data, or visualizing audit findings in the context of code structure.

trailofbits/audit-context-building

Enables ultra-granular, line-by-line code analysis to build deep architectural context before vulnerability or bug finding.

trailofbits/audit-prep-assistant

Prepares codebases for security review using Trail of Bits' checklist. Helps set review goals, runs static analysis tools, increases test coverage, removes dead code, ensures accessibility, and generates documentation (flowcharts, user stories, inline comments).

trailofbits/burpsuite-project-parser

Searches and explores Burp Suite project files (.burp) from the command line. Use when searching response headers or bodies with regex patterns, extracting security audit findings, dumping proxy history or site map data, or analyzing HTTP traffic captured in a Burp project.

trailofbits/cairo-vulnerability-scanner

Scans Cairo/StarkNet smart contracts for 6 critical vulnerabilities including felt252 arithmetic overflow, L1-L2 messaging issues, address conversion problems, and signature replay. Use when auditing StarkNet projects.

trailofbits/cargo-fuzz

cargo-fuzz is the de facto fuzzing tool for Rust projects using Cargo. Use for fuzzing Rust code with libFuzzer backend.

trailofbits/chrome-mcp-troubleshooting

Diagnose and fix Claude in Chrome MCP extension connectivity issues. Use when mcp__claude-in-chrome__* tools fail, return "Browser extension is not connected", or behave erratically.

trailofbits/claude-in-chrome-troubleshooting

Diagnose and fix Claude in Chrome MCP extension connectivity issues. Use when mcp__claude-in-chrome__* tools fail, return "Browser extension is not connected", or behave erratically.

trailofbits/code-improver

Runs an autonomous review-and-fix improvement loop over any code target — a skill, plugin, module, or directory — using a reviewer the user names: any installed skill or agent. Keeps a cross-round findings ledger, escalates when fixes stop converging, and guards scope mechanically. Use when asked to 'improve this code until review passes', 'run an improvement loop with <reviewer>', or to iterate review-and-fix with a specific reviewer. For skills prefer the skill-improver entry; for a branch prefer pr-improver.

trailofbits/code-maturity-assessor

Systematic code maturity assessment using Trail of Bits' 9-category framework. Analyzes codebase for arithmetic safety, auditing practices, access controls, complexity, decentralization, documentation, MEV risks, low-level code, and testing. Produces professional scorecard with evidence-based ratings and actionable recommendations.

trailofbits/codeql

Scans a codebase for security vulnerabilities using CodeQL's interprocedural data flow and taint tracking analysis. Triggers on "run codeql", "codeql scan", "codeql analysis", "build codeql database", or "find vulnerabilities with codeql". Supports "run all" (security-and-quality + security-experimental suites) and "important only" (high-precision security findings) scan modes. Also handles creating data extension models and processing CodeQL SARIF output.

trailofbits/constant-time-analysis

Detects timing side-channel vulnerabilities in cryptographic code. Use when implementing or reviewing crypto code, encountering division on secrets, secret-dependent branches, or constant-time programming questions in C, C++, Go, Rust, Swift, Java, Kotlin, C#, PHP, JavaScript, TypeScript, Python, or Ruby.

trailofbits/constant-time-testing

Constant-time testing detects timing side channels in cryptographic code. Use when auditing crypto implementations for timing vulnerabilities.

trailofbits/cosmos-vulnerability-scanner

Scans Cosmos SDK blockchain modules and CosmWasm contracts for consensus-critical vulnerabilities — chain halts, fund loss, state divergence. 25 core + 16 IBC + 10 EVM + 3 CosmWasm patterns. Use when auditing custom x/ modules, reviewing IBC integrations, or assessing pre-launch chain security. Updated for SDK v0.53.x.

関連スキル