Communitygithub.com

trailofbits/modern-cpp

指导 C++ 代码向现代惯用法(C++20/23/26)演进。适用于编写新 C++ 代码、现代化遗留模式或处理安全关键型 C++ 代码。用智能指针替代裸指针,用概念替代 SFINAE,用 std::print 替代 printf,用 std::expected 替代错误码。

modern-cpp 是什么?

该技能由 Trail of Bits 提供,专注于指导 C++ 开发采用现代惯用法(C++20/23/26),同时特别强调安全性。它提供了一套全面的规则,以消除常见漏洞类别(如内存泄漏、缓冲区溢出和未定义行为),并减少样板代码。该技能适用于多种平台,包括 Claude Code、Cursor 和 Codex,因为它以通用的 AI Agent 技能规范(SKILL.md)形式呈现。其主要功能包括:一份包含 30 多种模式的迁移表,用于将陈旧的反模式(如裸指针和 printf)替换为现代替代方案(如智能指针、std::format 和 std::expected);一个功能优先级决策树,用于根据实际情况(编写新代码、现代化现有代码或处理安全关键型代码)指导开发;以及编译器加固的快速参考(包括标志、清理器和加固的 libc++)。它还会反驳常见的错误观念,并提供一份最佳实践清单,以确保代码库更安全、更易于维护。

兼容平台~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++

使用 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类型安全、无隐晦的 UB
原始 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 中运行清理器
|   +-- 参见 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 + 手动汇合C++20
指定初始化器位置结构体初始化C++20
std::expected<T,E>错误码、边界处的异常C++23
std::print / std::printlnprintf、std::cout <<C++23
推导 thisCRTP、const/non-const 重复C++23
std::flat_map针对读取密集型使用的 std::mapC++23
一元 std::optional嵌套的 if 检查 optionalC++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 中的清理器 — 至少使用 ASan + UBSan;并发代码使用 TSan
  • 警告标志 — -Wall -Wextra -Wpedantic -Werror

请参见 compiler-hardening.md。

第 3 层:规划使用(C++26,值得围绕其重构)

反射是 C++26 中最具变革性的特性。它消除了:

  • 序列化样板代码(一个通用函数替代每个结构体的 to_json)
  • 代码生成器(protobuf codegen、Qt MOC)
  • 基于宏的注册和枚举到字符串的黑客手段

GCC 16(2026 年 4 月)已合并反射。规划新代码以从中受益。

第 4 层:关注(C++26,需要成熟)

  • 契约(pre/post/contract_assert)— 比 assert() 更好,但不支持虚函数,且编译器支持有限。谨慎采用,适用于新的 API 边界。
  • std::execution(发送器/接收器)— 强大的异步框架,但学习曲线陡峭,没有附带调度器,且文档匮乏。等待生态系统成熟。

请参见 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(本质上无 UB)
  • 当忽略返回值很可能是一个错误时,将函数标记为 [[nodiscard]]
  • 优先使用值语义;使用 std::variant 替代 union,使用 enum class 替代 enum
  • 在声明时初始化所有变量

继续阅读

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.

相关技能