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 慣用法,以消除漏洞類別並減少樣板程式碼。它提供了一個豐富的反模式對照表,涵蓋 12 種以上常見的舊式寫法(如 new/delete、C 陣列、printf、SFINAE、union),並推薦現代替代方案(如 std::make_unique、std::array、std::format、概念、std::variant)。技能還包含一個決策樹,幫助使用者根據「撰寫新程式碼」、「現代化既有程式碼」、「安全關鍵程式碼」或「使用 C++26 功能」等情境選擇合適的策略。此外,它將 C++ 功能分為四個等級:Tier 1(C++20/23,立即使用)、Tier 2(編譯器強化、消毒器,無需升級標準)、Tier 3(C++26 反射,值得重構)、Tier 4(契約、std::execution,待觀察),並提供編譯器強化旗標的快速參考和常見錯誤推論的反駁表。此技能旨在協助開發者在所有平台上撰寫更安全、更現代的 C++ 程式碼。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/trailofbits/skills/tree/main/plugins/modern-cpp/skills/modern-cpp

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

現代 C++ (Modern 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消除記憶體洩漏、雙重釋放
原始擁有者指標 (Raw owning pointers)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)工具可見、可配置
手動 CRTP推導 this (C++23)更簡單、無樣板程式碼
巨集程式碼生成反射 (C++26)零開銷、可組合

請參閱 anti-patterns.md 取得完整對照表(30 種以上模式)。

決策樹

你在做什麼?
|
+-- 撰寫新的 C++ 程式碼?
|   +-- 預設使用現代慣用法 (C++20/23)
|   +-- 選擇編譯器支援的最新標準
|   +-- 參閱下方功能分級
|
+-- 現代化現有程式碼?
|   +-- 從第 1 級 (C++20/23) 的替代方案開始
|   +-- 優先依據安全性影響 (記憶體 > 型別 > 風格)
|   +-- 參閱 anti-patterns.md 的遷移對照表
|
+-- 安全關鍵的程式碼?
|   +-- 啟用編譯器強化旗標 (見下方)
|   +-- 啟用強化版 libc++ 模式
|   +-- 在 CI 中執行消毒器 (Sanitizers)
|   +-- 參閱 safe-idioms.md 與 compiler-hardening.md
|
+-- 使用 C++26 功能?
    +-- 反射:是的,為它做規劃 (GCC 16+)
    +-- 契約:謹慎使用,用於新的 API 邊界
    +-- std::execution:等待生態系統成熟
    +-- 參閱 cpp26-features.md

功能分級

功能根據當前的實用性進行分級,而非標準版本。

第 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 + 手動 joinC++20
指定初始化 (Designated initializers)位置式結構體初始化C++20
std::expected<T,E>錯誤碼、邊界例外C++23
std::print / std::printlnprintf、std::cout <<C++23
推導 this (Deducing this)CRTP、const/non-const 重複C++23
std::flat_mapstd::map (適用於讀取密集型場景)C++23
std::optional 的單子操作 (Monadic)對 optional 的巢狀 if 檢查C++23

請參閱 cpp20-features.md 與 cpp23-features.md。

第 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 中的消毒器 (Sanitizers) — 最低限度使用 ASan + UBSan;並行程式碼再加入 TSan
  • 警告旗標 — -Wall -Wextra -Wpedantic -Werror

請參閱 compiler-hardening.md。

第 3 級:為它做規劃 (C++26,值得圍繞其重構)

反射 (Reflection) 是最具變革性的 C++26 功能。它消除了:

  • 序列化樣板程式碼 (一個通用函式取代每個結構體的 to_json)
  • 程式碼生成器 (protobuf codegen、Qt MOC)
  • 基於巨集的註冊與枚舉轉字串的 hack

GCC 16 (預計 2026 年 4 月) 已合併反射功能。規劃新的程式碼以利用此優勢。

第 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 取得完整指南。

應拒絕的常見推論

推論為什麼是錯的

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.

相關技能