Modern Cpp
Trail of BitsOfficialPublished by Trail of Bits
- Skill
- Guidelines
- Software development
- CC-BY-SA-4.0
- No issues found
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
Download the skill as a ZIP:
https://autogineer.com/agent-skills/trailofbits/modern-cpp/downloadUnzip 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
| Avoid | Use Instead | Why |
|---|---|---|
new/delete | std::make_unique, std::make_shared | Eliminates leaks, double-free |
| Raw owning pointers | std::unique_ptr, std::shared_ptr | RAII ownership semantics |
C arrays (int arr[N]) | std::array<int, N> | Bounds-aware, value semantics |
| Pointer + length params | std::span<T> | Non-owning, bounds-checkable |
printf / sprintf | std::format, std::print | Type-safe, no buffer overflow |
C-style casts (int)x | static_cast<int>(x) | Explicit intent, auditable |
#define constants | constexpr variables | Scoped, typed, debuggable |
SFINAE / enable_if | Concepts + requires | Readable constraints and errors |
| Error codes + out params | std::expected<T, E> | Composable, type-safe errors |
union | std::variant | Type-safe, no silent UB |
Raw mutex.lock()/unlock() | std::scoped_lock | Exception-safe, no deadlocks |
std::thread | std::jthread | Auto-join, stop token support |
assert() macro | contract_assert (C++26) | Visible to tooling, configurable |
| Manual CRTP | Deducing this (C++23) | Simpler, no template boilerplate |
| Macro code generation | Reflection (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.mdFeature Tiers
Features are ranked by practical usability today, not by standard version.
Tier 1: Use Today (C++20/23, solid compiler support)
| Feature | Replaces | Standard |
|---|---|---|
Concepts + requires | SFINAE, enable_if | C++20 |
| Ranges + views | Raw iterator loops | C++20 |
std::span<T> | Pointer + length | C++20 |
std::format | sprintf, iostream chains | C++20 |
Three-way comparison <=> | Manual comparison operators | C++20 |
std::jthread | std::thread + manual join | C++20 |
| Designated initializers | Positional struct init | C++20 |
std::expected<T,E> | Error codes, exceptions at boundaries | C++23 |
std::print / std::println | printf, std::cout << | C++23 |
Deducing this | CRTP, const/non-const duplication | C++23 |
std::flat_map | std::map for read-heavy use | C++23 |
Monadic std::optional | Nested if-checks on optionals | C++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=zeroHardened libc++ —
-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FASTfor ~0.3% overhead bounds-checkingSanitizers in CI — ASan + UBSan as minimum; TSan for concurrent code
Warning flags —
-Wall -Wextra -Wpedantic -Werror
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 thanassert(), 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,nowClang-Specific
-Wunsafe-buffer-usageHardened libc++ (Clang/libc++ only)
-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FASTGoogle 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
| Rationalization | Why 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::spanover pointer + length for function parameters[ ] Use
std::expectedfor 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/constevalwhere possible (UB-free by design)[ ] Mark functions
[[nodiscard]]when ignoring the return value is likely a bug[ ] Prefer value semantics; use
std::variantoverunion,enum classoverenum[ ] Initialize all variables at declaration
Read Next
anti-patterns.md — Full legacy-to-modern migration table (30+ patterns)
cpp20-features.md — Concepts, ranges, span, format, coroutines
cpp23-features.md — expected, print, deducing this, flat_map
cpp26-features.md — Reflection, contracts, memory safety improvements
compiler-hardening.md — Flags, sanitizers, hardened libc++
safe-idioms.md — Security patterns by vulnerability class
Files
- ATTRIBUTION.mdAdded by AutoGineer924 B
- LICENSELicence file added by AutoGineer19.7 KiB
- SKILL.md8.5 KiB
- references/anti-patterns.md5.5 KiB
- references/compiler-hardening.md7.3 KiB
- references/cpp20-features.md7.0 KiB
- references/cpp23-features.md7.0 KiB
- references/cpp26-features.md7.5 KiB
- references/safe-idioms.md8.1 KiB
references/safe-idioms.md
Safe C++ Idioms
Security patterns organized by vulnerability class. Each section explains what exploitable bugs the pattern prevents and what modern C++ features eliminate them.
Memory Safety
Ownership: Smart Pointers
Use smart pointers for all owning relationships. Raw pointers are only for non-owning observation.
// Unique ownership (default choice)
auto widget = std::make_unique<Widget>(args...);
process(*widget); // borrow via reference
// Shared ownership (only when genuinely shared)
auto shared = std::make_shared<Config>(args...);
auto copy = shared; // reference count incremented
// Non-owning observation
Widget* observer = widget.get(); // does NOT own, must not delete
std::weak_ptr<Config> watcher = shared; // non-owning, expires safelySelection guide:
std::unique_ptr— default. Zero overhead vs raw pointer. Use for exclusive ownership.std::shared_ptr— only when multiple owners genuinely need to extend lifetime. Has overhead (refcount, control block).std::weak_ptr— observe shared objects without preventing destruction. Use to break cycles.Raw
T*/T&— non-owning only. Neverdeletea raw pointer you didn'tnew.
Non-Owning Views
// DANGEROUS: pointer + length — no size information
void process(const char* data, size_t len);
// SAFE: carries size, bounds-checkable
void process(std::span<const char> data);
// DANGEROUS: null-terminated assumption
void log(const char* message);
// SAFE: carries length, works with string and string_view
void log(std::string_view message);Rules:
Function parameters:
std::span<T>for arrays,std::string_viewfor stringsReturn values: return owned types (
std::vector,std::string), not viewsNever return a
spanorstring_viewto a local
Optional vs Nullable Pointers
// DANGEROUS: null pointer used as "no value"
Widget* find(int id); // caller might forget to check
// SAFE: explicit optionality
std::optional<Widget> find(int id); // caller must unwrap
// Check before use
if (auto w = find(42)) {
use(w.value()); // or *w
}Value Semantics by Default
Prefer value types over heap-allocated pointer indirection. C++26 adds std::indirect<T> and std::polymorphic<T> for cases where heap allocation is needed but value semantics are desired.
Type Safety
Variant Over Union
// DANGEROUS: union — accessing wrong member is UB
union Value { int i; double d; std::string s; }; // UB: string in union
// SAFE: variant — type-checked access
std::variant<int, double, std::string> value;
value = "hello";
// Visit pattern — compiler ensures all types handled
std::visit([](auto&& v) { std::println("{}", v); }, value);
// Throws std::bad_variant_access if wrong type
auto& s = std::get<std::string>(value);Safe Type Punning
// DANGEROUS: reinterpret_cast — undefined behavior for most types
float f = 3.14f;
int bits = *reinterpret_cast<int*>(&f); // UB!
// SAFE: bit_cast — defined behavior, constexpr-compatible
int bits = std::bit_cast<int>(f); // OK, well-definedEnum Class
// DANGEROUS: plain enum — implicit int conversion, leaks names
enum Color { Red, Green, Blue };
int x = Red; // compiles silently
if (Red == 0) // compiles silently
// SAFE: enum class — scoped, no implicit conversion
enum class Color : uint8_t { Red, Green, Blue };
// int x = Color::Red; // compile error
// if (Color::Red == 0) // compile error
auto c = Color::Red; // must use scopePreventing Misuse
// Mark functions where ignoring the return is likely a bug
[[nodiscard]] std::expected<Data, Error> load(const Path& p);
// Prevent implicit conversions
class UserId {
public:
explicit UserId(int64_t id) : id_(id) {}
// UserId u = 42; // compile error — must be explicit
private:
int64_t id_;
};
// Document why an overload is forbidden (C++26)
void process(std::string_view s);
void process(std::nullptr_t) = delete("passing nullptr is a bug — use empty string");Integer Safety
Narrowing Detection
#include <utility>
void safe_convert(int64_t big_value) {
// CHECK: is the value representable in the target type?
if (std::in_range<int32_t>(big_value)) {
int32_t small = static_cast<int32_t>(big_value);
use(small);
} else {
handle_overflow();
}
}Saturation Arithmetic (C++26)
#include <numeric>
// For signal processing, image manipulation, counters
uint8_t pixel = std::add_sat<uint8_t>(200, 100); // 255, not 44
// Useful for counters that should not wrap
size_t count = std::add_sat(count, increment);Compiler Warnings
Enable -Wconversion and -Wsign-conversion to catch implicit narrowing at compile time. These flags alone prevent a significant class of integer bugs.
Concurrency Safety
Lock Management
// DANGEROUS: manual lock/unlock — exception-unsafe, easy to forget
std::mutex mtx;
mtx.lock();
do_work(); // if this throws, mutex is never unlocked
mtx.unlock();
// SAFE: scoped_lock — exception-safe, supports multiple mutexes
{
std::scoped_lock lock(mtx);
do_work(); // mutex released when lock goes out of scope
}
// Multiple mutexes — deadlock-free (sorted lock acquisition)
std::scoped_lock lock(mutex_a, mutex_b);Thread Management
// DANGEROUS: std::thread — forgetting join() calls std::terminate
std::thread t(work);
// if exception before join → crash
// SAFE: jthread — auto-joins, supports cooperative cancellation
std::jthread t([](std::stop_token stoken) {
while (!stoken.stop_requested()) {
do_work();
}
});
// destructor calls request_stop() then join()Atomics
// DANGEROUS: volatile does NOT provide atomicity or ordering
volatile int counter = 0; // data race in multi-threaded code
// SAFE: atomic with explicit memory ordering
std::atomic<int> counter{0};
counter.fetch_add(1, std::memory_order_relaxed); // specify orderingInitialization Safety
constexpr / consteval
Computation at compile time is UB-free by design — the compiler rejects any undefined behavior in constant expressions.
constexpr int factorial(int n) {
// If this has UB (e.g., signed overflow), it's a compile error
int result = 1;
for (int i = 2; i <= n; ++i) result *= i;
return result;
}
consteval int must_be_compile_time(int n) {
return factorial(n); // guaranteed compile-time evaluation
}Always Initialize
// DANGEROUS: uninitialized variable
int x; // indeterminate value (erroneous behavior in C++26)
use(x); // bug
// SAFE: initialize at declaration
int x = 0;
int y{}; // value-initialized (zero for scalars)
auto z = compute_value();Enable -ftrivial-auto-var-init=zero to catch cases you miss.
Rule of Five / Zero
// Rule of Zero: prefer this — let the compiler generate everything
struct Config {
std::string name;
std::vector<int> values;
// No destructor, copy/move constructors, or assignment needed
// Compiler-generated versions do the right thing
};
// Rule of Five: if you must manage a resource manually
class FileHandle {
int fd_;
public:
~FileHandle();
FileHandle(const FileHandle&);
FileHandle& operator=(const FileHandle&);
FileHandle(FileHandle&&) noexcept;
FileHandle& operator=(FileHandle&&) noexcept;
};
// But prefer RAII wrappers (unique_ptr with custom deleter) over thisIterator Safety
Prefer Algorithms Over Raw Loops
// RISKY: off-by-one, iterator invalidation
for (auto it = vec.begin(); it != vec.end(); ++it) {
if (should_remove(*it)) {
vec.erase(it); // BUG: invalidates iterator
}
}
// SAFE: erase-remove idiom
std::erase_if(vec, should_remove); // C++20
// SAFE: range-based algorithms
auto results = data
| std::views::filter(is_valid)
| std::views::transform(process);Iterator Invalidation Awareness
Know which operations invalidate iterators on which containers. When in doubt, use indices or rebuild the container. Trail of Bits' Itergator tool detects iterator invalidation bugs via CodeQL.
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