Modern C++ patterns: RAII and ownership, rule of zero/five, exceptions and error handling, API and ABI boundaries, templates, and CMake tooling. Use when writing, reviewing, refactoring, or debugging C++, working with smart pointers, move semantics, memory leaks, template errors, or gtest. For plain C, see ia-c-systems.
--- name: ia-cpp-systems class: language description: >- Modern C++ patterns: RAII and ownership, rule of zero/five, exceptions and error handling, API and ABI boundaries, templates, and CMake tooling. Use when writing, reviewing, refactoring, or debugging C++, working with smart pointers, move semantics, memory leaks, template errors, or gtest. For plain C, see ia-c-systems. paths: - "**/*.cpp" - "**/*.hpp" - "**/*.cc" - "**/*.hh" - "**/*.cxx" - "**/*.h" - "**/CMakeLists.txt" - "**/*.cmake" --- # C++ Systems & Libraries Covers C++17 as the baseline, with C++20 features called out where a project's standard allows them. For plain C (manual lifetimes, status enums, native extensions), see the `ia-c-systems` skill. ## Working rules - Make resource ownership explicit and use RAII for release on every exit path. - Keep borrowed views within backing-storage lifetimes and review copy/move behavior when special members change. - Follow the project's error model and supported language standard. - Preserve ABI and avoid invoking unknown callbacks while holding locks or invalidatable container iterators. ## Repo conventions outrank this skill Check `CMakeLists.txt` for `CXX_STANDARD`, read `.clang-format` and `.clang-tidy`, and read two adjacent translation units before writing. Where they conflict with the rules below, they win. The conflicts that actually happen: | Local constraint | Consequence | |---|---| | `-fno-exceptions` | Error handling is codes or `expected`-alikes. Constructors cannot report recoverable failure, so use a fallible factory or construct a valid fallback state. `new (std::nothrow)` only where the project's OOM policy is to observe null and recover; plain `new` is fine where the policy is termination | | Standard pinned below C++17 | No `std::optional`/`string_view`/structured bindings/`if constexpr`; check before using any | | Public header is ABI-stable | No layout changes, no inline-function changes, no added virtuals: load the ABI reference | | Embedded or freestanding target | No RTTI, no dynamic allocation in hot paths, possibly no STL containers | ## Ownership and RAII Every resource has exactly one owner, and that owner is an object whose destructor releases it. A raw `new` or `delete` in application code is a defect. - `std::unique_ptr<T>` for sole ownership. It is the default; it costs nothing over a raw pointer. - `std::shared_ptr<T>` only where lifetime is genuinely shared and cannot be expressed as "the owner outlives the users". Reach for it third, not first. - `std::weak_ptr<T>` to break ownership cycles. LeakSanitizer does report a cycle that is unreachable from any root, but not one still reachable from a global or other registered root, and detection varies by platform and configuration. Do not rely on the sanitizer to find these. - Raw `T*` and `T&` mean **non-owning observation**, and are correct in that role. A parameter taking `unique_ptr` by value is announcing that it consumes ownership; one taking `T*` is announcing it does not. - `std::span<T>` (C++20) or a pointer-plus-length pair for a borrowed contiguous range **in a new public API**, since `const std::vector<T>&` there refuses every other container. On a C++17 baseline, or for internal code whose callers all hold vectors anyway, `const std::vector<T>&` is fine and simpler. **Rule of zero**: a class that owns nothing declares no destructor, no copy, and no move. Composing members that manage themselves gets all five special members correct for free. **Rule of five**: declaring any one of destructor, copy constructor, copy assignment, move constructor, or move assignment obliges the author to reason about all five. A user-declared destructor suppresses the implicit move operations, so a class that gained a destructor silently started deep-copying where it used to move. ## Discipline - Preserve behavior and API compatibility unless a break was requested. A public header change is a decision, not a cleanup. - Do not introduce a template, an inheritance hierarchy, or a policy parameter for a single call site. - `#include` what the file uses; do not rely on transitive includes from another header. - No `using namespace` at namespace scope in a header. Fully qualify instead, or scope the `using` to a function body. - When a constraint forces a deviation, comment at the deviation site and state the constraint. ## Verify - Build clean with `-Wall -Wextra -Wpedantic -Wshadow -Wconversion -Werror` - `clang-tidy` reports no new findings on the diff - Tests pass under `-fsanitize=address,undefined` with zero reports - Any threaded code touched by the change exercised under TSan with zero reports; the warning bundle above does not catch lock misuse - `clang-format --dry-run --Werror` produces no diff - No new raw `new`/`delete`, no new `shared_ptr` where `unique_ptr` suffices - Any class that gained a destructor has its move operations reviewed ## Task-specific references Read the relevant reference before implementing or reviewing the matching behavior: - For constness, errors, API/ABI changes, templates, or standard-library behavior: [value-and-interface-design.md](./references/value-and-interface-design.md). - For threading, compiler setup, tests, or build analysis: [concurrency-and-verification.md](./references/concurrency-and-verification.md). Existing specialized references, when the corresponding topic applies: - [api-and-abi.md](./references/api-and-abi.md). - [cmake-and-tooling.md](./references/cmake-and-tooling.md). - [legibility-standard.md](./references/legibility-standard.md).
don't have the plugin yet? install it then click "run inline in claude" again.
converted original reference doc into structured skill format with explicit inputs, step-by-step procedure, decision trees for language/exception models/ABI, and verifiable success criteria aligned to Implexa standards.
Use this skill when writing, reviewing, refactoring, or debugging C++17+ code. covers RAII, ownership models, the rule of zero/five, exception handling, template correctness, move semantics, memory safety, ABI stability, and CMake. if you're working with smart pointers, debugging memory leaks, untangling template errors, or integrating gtest, this is your reference. for plain C with manual lifetimes and status enums, see ia-c-systems instead.
CMakeLists.txt for CXX_STANDARD (baseline is C++17; C++20 features called out where applicable).clang-format and .clang-tidy for project standards; build with -Wall -Wextra -Wpedantic -Wshadow -Wconversion -Werror-fno-exceptions (error codes / expected<T, E> only), or freestanding (no dynamic allocation in hot paths, possibly no RTTI)-fsanitize=address,undefined for memory checks; ThreadSanitizer for any threaded code touchedEstablish ownership model: identify every resource (memory, file handle, lock, etc.). assign exactly one owner. that owner is an object whose destructor releases the resource on all exit paths (normal return, exception, goto, early exit).
Choose smart pointer or raw pointer for the declared type:
std::unique_ptr<T> for sole ownership (default; zero overhead vs. raw pointer)std::shared_ptr<T> only if lifetime is genuinely shared across independent subtrees and cannot be expressed as "owner outlives users"std::weak_ptr<T> to break cycles; note: LeakSanitizer may not detect cycles reachable from globals or registered rootsT* and T& for non-owning observation only; a parameter taking unique_ptr<T> signals consumption; one taking T* signals non-ownershipstd::span<T> (C++20) or pointer-plus-length for borrowed contiguous ranges in new public APIs; on C++17 or for internal code, const std::vector<T>& is simpler if all callers use vectorsApply rule of zero or rule of five:
Handle errors according to project model:
noexcept where guaranteed. wrap resource acquisition in RAII or use std::make_unique / std::make_shared-fno-exceptions: use error codes, std::optional<T>, or expected<T, E> (libc++ and others provide this). constructors cannot report recoverable failure; use a fallible factory function or construct a valid fallback. use new (std::nothrow) only where OOM policy is observation and recovery; plain new is acceptable where OOM policy is terminationReview constness and API boundaries:
using namespace at namespace scope in headers; fully qualify or scope using to function bodyHandle special cases for containers and iterators:
Template instantiation and compilation:
.cpp with explicit instantiation listif constexpr (C++17+) to specialize at compile time; do not rely on SFINAE where concept-like clarity is neededBuild and verify:
-Wall -Wextra -Wpedantic -Wshadow -Wconversion -Werrorclang-tidy on the diff; fix all new findings-fsanitize=address,undefined; zero reports required-Wall flags do not catch lock misuseclang-format --dry-run --Werror; zero diffs requirednew, delete, or shared_ptr substitution that should be unique_ptr; any class that gained a destructor must have move operations reviewedIf exceptions are enabled (default): use try-catch for recovery; wrap resource acquisition in RAII or smart pointers; mark functions noexcept only if genuinely safe. goto Procedure step 4 (exceptions enabled).
Else if -fno-exceptions is set: error handling uses return codes, std::optional<T>, or expected<T, E>. constructors cannot signal recoverable failure, so provide a factory function or construct a valid fallback state. use new (std::nothrow) only if OOM recovery is the policy; plain new is fine if OOM terminates. goto Procedure step 4 (-fno-exceptions).
Else if freestanding or embedded target: no RTTI, no dynamic allocation in performance-critical paths, possibly no STL containers. allocate on stack or use preallocated pools. goto Procedure step 4 (freestanding).
If the C++ standard is pinned below C++17: do not use std::optional, std::string_view, structured bindings, or if constexpr. check before using any C++17+ feature. goto Procedure step 7 (template instantiation).
If a public header is ABI-stable: changes to layout, inline functions, or virtual methods break binary compatibility. load the ABI reference document. do not modify inline function bodies, rearrange member variables, or add virtuals to existing classes. goto Procedure step 6 (API boundaries).
If a class gained a destructor: user-declared destructors suppress implicit move, causing silent deep-copy. explicitly define or delete the move constructor and move assignment. review copy semantics too. goto Procedure step 3 (rule of five).
If raw new or delete appears in the diff: this is a defect in application code. replace with std::make_unique or std::make_shared. goto Procedure step 2 (ownership).
If shared_ptr is used but single ownership is apparent: replace with unique_ptr. shared_ptr has higher overhead and obscures ownership semantics. goto Procedure step 2 (ownership).
If an iterator is held across mutation or callback invocation: the iterator may be invalidated. either copy the value, break the operation into safe chunks, or use a non-invalidating container (e.g. std::list, std::map). goto Procedure step 6 (containers and iterators).
success means:
-Wall -Wextra -Wpedantic -Wshadow -Wconversion -Werror produces zero warningsclang-tidy output on the diff shows no new findings-fsanitize=address,undefined with zero reportsclang-format --dry-run --Werror produces no diffsnew or delete in application code; no shared_ptr where unique_ptr sufficesexpected<T, E>, etc.)you know this skill worked when:
AddressSanitizer and UndefinedBehaviorSanitizer produce zero reports on the test suiteThreadSanitizer produces zero reports if threading is involved