cpp
Use when writing, reviewing, modernizing, building, or debugging C++ - RAII and resource lifetime, smart-pointer ownership, move semantics and the Rule of Zero/Five, target-based CMake with FetchContent, and killing undefined behavior with ASan/UBSan/TSan plus clang-tidy. NOT bor
Install
npx skills add https://github.com/ericrisco/rsc-harness/tree/main/skills/cpp
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install ericrisco-rsc-harness@llmmart
git clone https://github.com/ericrisco/rsc-harness.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole ericrisco/rsc-harness collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
Modern C++
Write, review, modernize, build, and debug C++ the way the C++ Core Guidelines intend: RAII for every resource, ownership made explicit through smart pointers and values, no undefined behavior by construction, and a target-based CMake build proven clean under sanitizers.
Targets C++20/23 for production today. C23 is ISO/IEC 14882:2024; WG21 froze C26's technical content on 2026-03-28 (ISO publication follows) — adopt C++26 features only behind confirmed compiler support. Compiler matrix:
| Compiler | C++23 | C++26 | Flag |
|---|---|---|---|
| GCC | since 11 | since 14 (GCC 16.1 covers most of C++26) | -std=c++23 / -std=c++26 |
| Clang | 13–18 progressively | in progress (Clang 23 dev) | -std=c++23 / -std=c++2c |
| MSVC | latest | partial | /std:c++23 / /std:c++latest |
Delegate: borrow-checker, Result/Option, cargo, ownership-via-compiler ->
rust — C++ buys safety with discipline (RAII + smart pointers +
sanitizers); do not conflate the mechanisms. Language-agnostic threat modeling, authz,
OWASP-class review -> secure-coding; the C++-specific
memory/UB controls (bounds, lifetime, integer overflow, format-string, sanitizers) stay
here. Containerizing and shipping the binary -> deployment;
this skill stops at the CMake build + a sanitizer-CI note.
Decision rules
Apply these on every C++ edit:
- Rule of Zero first. Manage resources with members that already do it (
vector,string,unique_ptr); write no destructor/copy/move at all. Why: hand-written special members are the #1 source of leaks and double-frees. - Value by default. Pass and return by value for small/copyable types; reach for the heap only when you need polymorphism, shared lifetime, or a large/stable address. Why: values can't dangle.
- Name the owner. Exactly one type owns each resource; everyone else borrows. Why: ambiguous ownership is how use-after-free is born.
make_unique/make_shared, nevernew. So no naked owning pointer ever exists.- Never an owning raw pointer. Raw pointers/references are non-owning borrows only.
- Borrow with
span/string_view/const T&. Pass a view, not a copy or an owner, for read access. Why: zero-copy, and the callee provably can't free what it doesn't own. constandconstexprby default. Why: the compiler enforces what you don't mutate and moves work off the hot path.- No UB by construction. No use-after-move, OOB index, signed overflow, uninitialized read, or data race.
- Sanitizers + warnings-as-errors in CI. Build and test under
-fsanitize=address,undefinedwith-Werror. - Target-based CMake only.
target_link_libraries/target_compile_features, never directory-levelinclude_directories/link_libraries. Why: directory commands leak flags globally and break composition.
Ownership & smart pointers
Pick the type from the need, not from habit:
| Need | Use |
|---|---|
| Exclusive owner, one place frees it | std::unique_ptr<T> |
| Genuinely shared lifetime (multiple owners, last one frees) | std::shared_ptr<T> |
Observe / break a shared_ptr cycle, no ownership |
std::weak_ptr<T> (.lock() to use) |
| Read-only borrow of contiguous range / string | std::span<const T> / std::string_view |
| Borrow a single object, non-owning | const T& / T& / T* (never owning) |
| Small, copyable, value-like | the value itself — no heap |
Default to unique_ptr; only escalate to shared_ptr when ownership is actually shared, and
prove the shared case isn't a disguised single owner first — shared_ptr is not "the safe default."
// Bad: naked owning pointer; leaks on the throw, double-frees if you copy the handle.
Widget* w = new Widget(cfg);
configure(w); // if this throws, w leaks
delete w;
// Good: ownership is the type; freed exactly once, exception-safe, no delete to forget.
auto w = std::make_unique<Widget>(cfg);
configure(*w);
// Bad: parent <-> child shared_ptr cycle -> neither refcount hits zero -> leak forever.
struct Node { std::shared_ptr<Node> parent, child; };
// Good: child owns down, parent observes up. Cycle broken; lock() before use.
struct Node {
std::shared_ptr<Node> child; // owns
std::weak_ptr<Node> parent; // observes
};
if (auto p = node.parent.lock()) { /* p is a valid shared_ptr here */ }
When an object must hand out a shared_ptr to itself, derive from
std::enable_shared_from_this<T> and call shared_from_this() — never wrap this in a fresh
shared_ptr (that creates a second, independent refcount and a guaranteed double-free).
Deeper ownership/move reasoning -> references/move-and-templates.md.
RAII
Tie every resource — heap memory, file, socket, mutex, OS handle — to an object's lifetime; the
destructor releases it. Why: cleanup then happens on every exit path (return, exception, break)
for free, with no GC and no finally.
Use the standard guards before writing your own:
std::lock_guard lock(mtx_); // locks now, unlocks at scope end (C++17 CTAD)
std::scoped_lock locks(a_mtx, b_mtx); // multiple mutexes, deadlock-free acquisition
std::unique_lock lk(mtx_); // movable / deferrable, for condition_variable
std::ifstream in("data.txt"); // closes in its destructor
When you wrap a C resource yourself, make the destructor release and disable copies (Rule of Five
or unique_ptr with a custom deleter):
// RAII wrapper for a FILE*: closes once, can't leak, can't double-close.
class File {
public:
explicit File(const char* path, const char* mode) : f_(std::fopen(path, mode)) {
if (!f_) throw std::runtime_error("open failed");
}
~File() { if (f_) std::fclose(f_); }
File(const File&) = delete; // not copyable
File& operator=(const File&) = delete;
File(File&& o) noexcept : f_(std::exchange(o.f_, nullptr)) {} // move = steal
File& operator=(File&& o) noexcept { std::swap(f_, o.f_); return *this; }
FILE* get() const noexcept { return f_; }
private:
FILE* f_{};
};
// Even simpler when a deleter suffices — let unique_ptr own it (Rule of Zero):
auto fp = std::unique_ptr<FILE, decltype(&std::fclose)>(std::fopen("d", "r"), &std::fclose);
Move semantics & Rule of Zero/Five
Every expression is an lvalue (has a name, persists) or an rvalue (a temporary, about to die).
std::move does not move anything — it casts an lvalue to an rvalue so a move constructor/assignment
can steal its guts instead of copying. After you move from an object, it is valid but unspecified:
only assign to it or destroy it; reading it is use-after-move (a real bug ASan/UBSan won't catch — clang-tidy will).
- Rule of Zero (default): manage nothing by hand; let the compiler generate all five special members. This is correct for the vast majority of types.
- Rule of Five: the moment you write one of destructor / copy-ctor / copy-assign / move-ctor /
move-assign, you must reason about all five. If you're writing them, you probably should have used
a
unique_ptr/vectormember and gone back to Rule of Zero. - Move ops must be
noexcept. Why:std::vectorreallocation only moves elements instead of copying them when the move isnoexcept— otherwise it silently falls back to copies for the strong exception guarantee.
std::vector<std::string> v;
v.push_back(std::move(name)); // transfers the buffer; `name` is now empty-but-valid
// Bad: use-after-move — `name` holds an unspecified state here.
log(name); // don't. Reassign name first, or just don't read it.
Return local objects by value and let RVO / copy elision remove the copy — do not return std::move(local), which pessimizes by blocking elision. Take a forwarding reference T&& plus
std::forward<T>(x) only in generic code that must preserve value category.
Worked Rule-of-Five, perfect forwarding, CTAD, and C++20 concepts -> references/move-and-templates.md.
Avoiding UB (essentials)
Undefined behavior is the compiler's permission to assume the bug can't happen and optimize on that assumption — so the symptom is often a distant crash or a "works in Debug, breaks in Release." Pair static analysis (clang-tidy, cppcheck) with dynamic sanitizers; they catch disjoint bug classes.
| Sanitizer | Flag | Catches |
|---|---|---|
| AddressSanitizer | -fsanitize=address |
use-after-free, heap/stack buffer overflow, double-free |
| UndefinedBehaviorSanitizer | -fsanitize=undefined |
signed overflow, null/misaligned deref, bad shifts, invalid enum |
| ThreadSanitizer | -fsanitize=thread |
data races |
Combine ASan + UBSan in one build (-fsanitize=address,undefined); run TSan alone (it's
incompatible with ASan). Always add -fno-omit-frame-pointer -g for readable reports.
// Bad: returns a dangling reference into a destroyed temporary -> use-after-free, ASan fires.
const std::string& name() { std::string s = build(); return s; } // s dies at return
// Good: return by value; RVO makes it free.
std::string name() { return build(); }
The full catalog (lifetime, OOB, signed overflow, strict-aliasing, uninitialized, data races,
use-after-move), which sanitizer surfaces each, the canonical fix, and a "reading an ASan report"
walkthrough -> references/undefined-behavior.md.
Modern CMake (essentials)
Target-based only. State requirements on the target, never globally:
cmake_minimum_required(VERSION 3.21)
project(app LANGUAGES CXX)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON) # feeds clang-tidy / clangd
include(FetchContent) # FetchContent ships with CMake since 3.11
FetchContent_Declare(Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG v3.7.1)
FetchContent_MakeAvailable(Catch2) # its targets work just like find_package targets
add_executable(app src/main.cpp)
target_compile_features(app PRIVATE cxx_std_23) # request the standard on the target
target_compile_options(app PRIVATE -Wall -Wextra -Wpedantic -Werror)
target_link_libraries(app PRIVATE Catch2::Catch2WithMain)
Full template (src/include/tests layout, CMakePresets.json with debug/asan/release presets,
fmt + GoogleTest via FetchContent, per-compiler warning + sanitizer flags, install/export) ->
references/cmake.md.
Standard-library idioms
Reach for the library before hand-rolling:
#include <algorithm>
#include <ranges>
#include <expected> // C++23
#include <format> // C++20
// Ranges over raw index loops — no off-by-one, no manual bounds.
auto evens = nums | std::views::filter([](int n){ return n % 2 == 0; });
std::ranges::sort(v);
// std::expected (C++23) over out-params / sentinel returns / exceptions for expected failure.
std::expected<Config, std::string> load(std::string_view path);
if (auto cfg = load(p)) use(*cfg); else log(cfg.error());
std::optional<User> find(int id); // "maybe absent", not a magic -1 / nullptr
std::span<const int> view(v); // borrow a contiguous range, no copy, no owner
auto [it, inserted] = m.try_emplace(k, val); // structured bindings
enum class Color { Red, Green }; // scoped, no implicit int conversions
std::string msg = std::format("{} of {}", i, n); // type-safe, no printf format-string UB
Prefer at() or a range-checked view when the index isn't provably in bounds; operator[] on a
bad index is UB, not an exception.
Testing & tooling
- Tests: Catch2 or GoogleTest pulled via
FetchContent(above); run them withctest. - Static analysis:
clang-tidy -p build(readscompile_commands.json) andcppcheck— they catch use-after-move, missingnoexcept, and lifetime bugs the compiler won't. - Dynamic analysis: run the test target under ASan+UBSan so tests prove no UB on covered paths.
- Format:
clang-format -iwith a checked-in.clang-format. - Local gate:
./scripts/verify.shfrom the project root runs format + an ASan/UBSan, warnings-as-errors build +ctest+ optional tidy/cppcheck. Missing tools are skipped, not failed.
Anti-patterns
| Rationalization | Reality / Do instead |
|---|---|
"I'll just new/delete carefully" |
One early return or throw and you leak/double-free. make_unique, always. |
| "A raw owning pointer is faster" | unique_ptr is zero-overhead; the cost is imaginary, the leak is real. |
"shared_ptr everywhere is the safe default" |
Shared ownership invites cycles + atomic refcount cost. Default unique_ptr; share only when truly shared. |
| "The C-style cast is fine, I know the type" | Use static_cast/dynamic_cast; C casts silently reinterpret and hide bugs. |
"Skip noexcept on the move ctor" |
vector then copies instead of moving on realloc. Mark moves noexcept. |
| "UB won't happen on my compiler" | UB lets the optimizer delete your checks; "works in Debug" proves nothing. |
| "No sanitizers, it ran fine" | It ran; it wasn't correct. Build+test under ASan+UBSan. |
| "A hand-rolled Makefile is simpler" | It rots and leaks flags. Target-based CMake is the contract. |
"v[i] is in range, I checked" |
If it's not provable, use .at() or a checked view; OOB is UB. |
"return std::move(local) to be fast" |
It blocks RVO and is slower. Return the local by value. |
"using namespace std; in a header" |
Pollutes every includer; ODR/ambiguity bugs. Never in a header. |
| "An out-param instead of returning the value" | Return by value (RVO) or optional/expected; out-params hide aliasing and UB. |
| "A global / singleton is simpler" | It's hidden shared mutable state -> data races + untestable. Inject it. |
Quick reference
| Task | Command / idiom |
|---|---|
| Configure + build | cmake -S . -B build && cmake --build build |
| Configure with sanitizers | cmake -S . -B build -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -g" |
| Test | ctest --test-dir build --output-on-failure |
| ASan + UBSan | -fsanitize=address,undefined -fno-omit-frame-pointer -g |
| ThreadSanitizer (alone) | -fsanitize=thread -g |
| Format | clang-format -i src/*.cpp |
| Static analysis | clang-tidy -p build src/*.cpp · cppcheck --enable=warning src/ |
| Std flag | GCC/Clang -std=c++23 (C++26: GCC -std=c++26, Clang -std=c++2c), MSVC /std:c++23 |
| Local gate | ./scripts/verify.sh (run in your project root) |
Project grounding (02-DOCS)
In a project with a 02-DOCS/ layer (the harness Karpathy wiki), read
02-DOCS/wiki/stack/cpp.md first and stay consistent with it. If it is missing or stale, write
this project's real choices there — std version and compiler matrix, CMake layout and presets, the
sanitizer/warning policy, the ownership/error conventions — index it in 02-DOCS/wiki/index.md
(the Knowledge map; root CLAUDE.md keeps only a pointer to it), and bump its Updated date in
the same change as any convention change. No 02-DOCS/ layer? Skip silently (optionally suggest
harness). Conventions are recorded, not gated — never block the task on this.
Files (rsc-harness)
-
evals
-
cases.yaml 3.9 KB
skill: cpp should_trigger: - prompt: "Modernize this C++ — it's full of new/delete and raw owning pointers, manual for loops, and C-style casts." why: "Modernizing legacy C++ (RAII, smart pointers, ranges, static_cast) is the skill's core use case." - prompt: "Who should own this object — a unique_ptr, a shared_ptr, or just a value? It gets passed around a lot." why: "Ownership design via the smart-pointer/value decision table is explicitly owned here." - prompt: "I'm getting a use-after-free and an occasional segfault under load. Find it." why: "Non-obvious, symptom-only trigger: the user never says 'smart pointer' or 'C++ idiom', but this routes here via the ASan + lifetime workflow." - prompt: "Write a CMakeLists.txt that pulls in Catch2 with FetchContent and turns on AddressSanitizer." why: "Target-based CMake with FetchContent + sanitizer build is a named trigger." - prompt: "Revisa este código C++ y dime si tengo una fuga de memoria." why: "Spanish review + memory-leak trigger; the description carries the Spanish phrasing 'fuga de memoria'." - prompt: "Should this move constructor be noexcept, and is my Rule of Five correct here?" why: "Move semantics / Rule of Five / noexcept-move is a core decision this skill makes." - prompt: "My program is fine in Debug but crashes in Release — is this undefined behavior, and how do I prove it with sanitizers?" why: "Non-obvious UB symptom ('works in Debug, breaks in Release'); routes here for the ASan/UBSan workflow, not a generic debugger." should_not_trigger: - prompt: "Fix this borrow-checker error and return a Result instead of panicking." route_to: "rust" why: "Borrow checker + Result/Option is Rust's compiler-enforced ownership, a different mechanism than C++ RAII discipline." - prompt: "Do a threat model and authz review of my service's permission boundaries and OWASP exposure." route_to: "secure-coding" why: "Language-agnostic threat modeling and authz/abuse review is delegated to secure-coding; only C++-specific memory/UB controls stay here." - prompt: "Write a multi-stage Dockerfile and GitHub Actions CI to build and ship my compiled binary." route_to: "deployment" why: "Containerizing and shipping the binary is delegated to deployment; this skill stops at the CMake build plus a sanitizer-CI note." - prompt: "Record our team's chosen C++ compiler flags and conventions in the project wiki and index them from CLAUDE.md." route_to: "harness" why: "Authoring/indexing the 02-DOCS workspace wiki is the harness skill's job; this skill only writes its own stack article when that layer already exists." - prompt: "Build a Go HTTP service with graceful shutdown and table-driven tests." route_to: "go" why: "A different sibling systems language; Go service work has no overlap with C++ mechanics." capability: - scenario: "Modernize a C++ class that owns a heap buffer via new[]/delete[] and a raw FILE*, and give it a sane CMake build." must_include: - "Replaces the owning raw buffer with std::unique_ptr or std::vector under Rule of Zero, OR keeps a hand-managed resource only via a correct Rule of Five with noexcept move operations" - "Wraps the FILE* in an RAII type whose destructor closes it (or uses std::fstream / unique_ptr with a custom deleter), so it closes on every exit path" - "Contains no new/delete and no owning raw pointers that escape; uses std::make_unique where heap is needed" - "CMake is target-based (target_compile_features(... cxx_std_23), target_link_libraries), not directory-level include_directories/link_libraries, and sets warnings-as-errors (-Werror / /WX)" - "Mentions building and testing under ASan+UBSan (-fsanitize=address,undefined) to prove no UB on covered paths" - "Uses const / value semantics and standard containers and algorithms over manual index loops where natural" -
README.md 1.1 KB
# Eval harness — `cpp` skill These cases are run by the rsc skill-eval harness (a Claude agent with the full skill catalog loaded), or read manually. They measure two things: **triggering** — that the `cpp` skill's description fires on each `should_trigger` prompt and stays quiet on the `should_not_trigger` near-misses, routing each of those to the named real sibling (`rust`, `secure-coding`, `deployment`, `go`, `harness`) instead; and **capability** — that, with `SKILL.md` and its references loaded, a graded model's generated C++ satisfies the `capability.must_include` rubric (RAII over raw resources, smart-pointer ownership, no `new`/`delete`, target-based CMake with warnings-as-errors, an ASan+UBSan build) and beats the no-skill baseline by a clear margin. Run 3–5 trials per prompt since LLM routing is non-deterministic; a prompt passes on a majority. No network is needed — the capability rubric is judged by reading the output against the points, and the verify.sh gate (compile under sanitizers + ctest) is exercised separately against a real project, not as part of these cases.
-
-
references
-
cmake.md 5.2 KB
# Modern CMake — full template Target-based, presets-driven, FetchContent for dependencies. CMake's current docs track 4.x; `FetchContent` has shipped since 3.11, and its imported targets are used with `target_link_libraries` exactly like `find_package` targets. The rule throughout: state requirements on the **target**, never globally. ## Layout ```text myproj/ CMakeLists.txt CMakePresets.json include/myproj/widget.hpp src/widget.cpp src/main.cpp tests/widget_test.cpp .clang-format .clang-tidy ``` ## Root CMakeLists.txt ```cmake cmake_minimum_required(VERSION 3.21) # 3.21+ for presets v3 and modern target features project(myproj VERSION 0.1.0 LANGUAGES CXX) # Export compile_commands.json so clang-tidy / clangd see exact flags. set(CMAKE_EXPORT_COMPILE_COMMANDS ON) # A reusable warnings interface target — link it into everything you own. add_library(myproj_warnings INTERFACE) if(MSVC) target_compile_options(myproj_warnings INTERFACE /W4 /permissive- /WX) else() target_compile_options(myproj_warnings INTERFACE -Wall -Wextra -Wpedantic -Wshadow -Wconversion -Wsign-conversion -Werror) endif() # --- library target --- add_library(widget src/widget.cpp) target_include_directories(widget PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:include>) target_compile_features(widget PUBLIC cxx_std_23) # the standard is a target property target_link_libraries(widget PRIVATE myproj_warnings) # --- executable target --- add_executable(app src/main.cpp) target_link_libraries(app PRIVATE widget myproj_warnings) # --- dependencies via FetchContent --- include(FetchContent) FetchContent_Declare(fmt GIT_REPOSITORY https://github.com/fmtlib/fmt.git GIT_TAG 11.0.2) FetchContent_Declare(Catch2 GIT_REPOSITORY https://github.com/catchorg/Catch2.git GIT_TAG v3.7.1) FetchContent_MakeAvailable(fmt Catch2) target_link_libraries(widget PUBLIC fmt::fmt) # --- tests --- enable_testing() add_executable(widget_test tests/widget_test.cpp) target_link_libraries(widget_test PRIVATE widget Catch2::Catch2WithMain myproj_warnings) include(Catch) # provided by Catch2; registers each TEST_CASE with ctest catch_discover_tests(widget_test) ``` Use GoogleTest instead of Catch2 by declaring `googletest` (GIT_TAG `v1.15.2`) and linking `GTest::gtest_main`; register with `include(GoogleTest)` + `gtest_discover_tests(...)`. ## CMakePresets.json Presets give every developer (and CI) identical, named configurations — no remembered flag soup. `debug` for day-to-day, `asan` for the sanitizer build the local gate uses, `release` for optimized output. ```json { "version": 3, "cmakeMinimumRequired": { "major": 3, "minor": 21, "patch": 0 }, "configurePresets": [ { "name": "debug", "binaryDir": "${sourceDir}/build/debug", "generator": "Ninja", "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" } }, { "name": "asan", "inherits": "debug", "binaryDir": "${sourceDir}/build/asan", "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug", "CMAKE_CXX_FLAGS": "-fsanitize=address,undefined -fno-omit-frame-pointer -g" } }, { "name": "release", "binaryDir": "${sourceDir}/build/release", "generator": "Ninja", "cacheVariables": { "CMAKE_BUILD_TYPE": "RelWithDebInfo" } } ], "buildPresets": [ { "name": "debug", "configurePreset": "debug" }, { "name": "asan", "configurePreset": "asan" }, { "name": "release", "configurePreset": "release" } ], "testPresets": [ { "name": "asan", "configurePreset": "asan", "output": { "outputOnFailure": true } } ] } ``` Drive it: ```bash cmake --preset asan # configure cmake --build --preset asan # build ctest --preset asan # test under ASan+UBSan ``` ## Sanitizer & warning flags per compiler | | GCC / Clang | MSVC | | --- | --- | --- | | Warnings-as-errors | `-Wall -Wextra -Wpedantic -Werror` | `/W4 /WX` | | ASan + UBSan | `-fsanitize=address,undefined -fno-omit-frame-pointer -g` | `/fsanitize=address` (no UBSan) | | TSan (run alone) | `-fsanitize=thread -g` | — | | Std | `-std=c++23` (`-std=c++26`/`-std=c++2c`) | `/std:c++23` (`/std:c++latest`) | Inject sanitizers per-config (the `asan` preset's `CMAKE_CXX_FLAGS`), not unconditionally — a release build must not carry them. ## clang-tidy / cppcheck With `CMAKE_EXPORT_COMPILE_COMMANDS=ON`, both tools read the exact per-file flags: ```bash clang-tidy -p build/debug src/widget.cpp src/main.cpp cppcheck --enable=warning,performance --project=build/debug/compile_commands.json ``` A minimal `.clang-tidy`: ```yaml Checks: 'clang-analyzer-*,bugprone-*,modernize-*,performance-*,cppcoreguidelines-*' WarningsAsErrors: 'clang-analyzer-*,bugprone-use-after-move' ``` ## Install / export (when you ship a library) ```cmake include(GNUInstallDirs) install(TARGETS widget EXPORT widgetTargets ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install(EXPORT widgetTargets NAMESPACE myproj:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/myproj) ``` Containerizing the resulting binary and CI pipelines -> `deployment`. -
move-and-templates.md 5.2 KB
# Move semantics, value categories, and modern generics ## Value categories in one pass Every expression has a category that decides whether it can be *moved from*: - **lvalue** — has a name and a stable identity (`x`, `obj.field`, `*p`). Persists past the expression. Binds to `T&` and `const T&`. - **prvalue** — a pure temporary with no name (`42`, `make()`, `a + b`). Binds to `T&&` and `const T&`. - **xvalue** — an "expiring" lvalue you've cast with `std::move(x)`; its resources may be stolen. `std::move` is just `static_cast<T&&>` — it *moves nothing*, it only relabels an lvalue as movable so an overload that steals (the move ctor/assign) is selected. After a move the source is in a **valid but unspecified** state: assigning to it or destroying it is fine; reading it is a bug. ## Rule of Zero vs Rule of Five Prefer **Rule of Zero**: hold resources in members that already manage themselves (`std::string`, `std::vector`, `std::unique_ptr`) and declare *none* of the five special members. The compiler generates correct copy/move/destroy for free. Write the five **only** when you manage a raw resource by hand — and treat that as a smell first (could a `unique_ptr` with a custom deleter do it?). The Rule of Five: if you declare any one of destructor / copy-ctor / copy-assign / move-ctor / move-assign, declare (or `= default`/`= delete`) all five, because declaring one suppresses others. ```cpp // Rule of Five for a hand-managed buffer. Note: every move op is noexcept. class Buffer { public: explicit Buffer(std::size_t n) : data_(new int[n]), size_(n) {} ~Buffer() { delete[] data_; } Buffer(const Buffer& o) : data_(new int[o.size_]), size_(o.size_) { std::copy(o.data_, o.data_ + size_, data_); } Buffer& operator=(const Buffer& o) { // copy-and-swap: strong guarantee, self-safe Buffer tmp(o); swap(tmp); return *this; } Buffer(Buffer&& o) noexcept // steal, leave o empty-but-valid : data_(std::exchange(o.data_, nullptr)), size_(std::exchange(o.size_, 0)) {} Buffer& operator=(Buffer&& o) noexcept { Buffer tmp(std::move(o)); swap(tmp); return *this; } void swap(Buffer& o) noexcept { std::swap(data_, o.data_); std::swap(size_, o.size_); } private: int* data_{}; std::size_t size_{}; }; ``` The equivalent Rule-of-Zero version is shorter and harder to get wrong: ```cpp class Buffer { public: explicit Buffer(std::size_t n) : data_(n) {} private: std::vector<int> data_; // vector is the five special members, done correctly }; ``` ## noexcept on moves — why it's load-bearing `std::vector` reallocation uses `move_if_noexcept`: it only *moves* its elements into the new buffer when the element's move constructor is `noexcept`; otherwise it falls back to *copying* to preserve the strong exception guarantee. A non-`noexcept` move ctor therefore silently turns every vector growth into a deep copy. Mark move operations `noexcept` whenever they can't throw (stealing pointers never throws). ## RVO and copy elision — don't fight it ```cpp // Good: the local is constructed directly in the caller's slot. No copy, no move. Widget make() { Widget w; configure(w); return w; } // Bad: std::move blocks NRVO and forces an actual move that elision would have removed. Widget make() { Widget w; return std::move(w); } // pessimization — drop the std::move ``` Return local objects by value, plainly. Only `std::move` a *member* or *parameter* out of a function (those aren't elision candidates). ## Perfect forwarding In a function template, `T&&` is a **forwarding reference** (it binds to lvalues *and* rvalues and preserves which it was). Pass it on with `std::forward<T>` so an rvalue argument stays movable and an lvalue stays an lvalue: ```cpp template <class T, class... Args> std::unique_ptr<T> make(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); // category preserved } ``` Use `std::forward` *only* with a deduced `T&&`. Inside a normal function, a parameter declared `T&&` where `T` is concrete is an rvalue reference, not forwarding — `std::move` it, don't `std::forward`. ## CTAD and C++20 concepts Class Template Argument Deduction lets you omit template args when the constructor implies them: ```cpp std::lock_guard lg(mtx); // deduces std::lock_guard<std::mutex> std::vector v{1, 2, 3}; // deduces std::vector<int> std::pair p{1, "x"}; // std::pair<int, const char*> ``` C++20 **concepts** constrain templates so errors fire at the call site with a readable message instead of deep inside instantiation, and they document intent: ```cpp #include <concepts> template <std::integral T> // only integers T gcd(T a, T b) { return b == 0 ? a : gcd(b, a % b); } template <class T> concept Drawable = requires(const T& t) { // a custom concept { t.draw() } -> std::same_as<void>; }; void render(const Drawable auto& shape) { shape.draw(); } // constrained abbreviated template ``` Prefer a concept over `enable_if`/SFINAE for new code: same constraint power, vastly better diagnostics, and it reads like a type. Combine concepts with `&&`/`||`, and use `requires` clauses for ad-hoc constraints the named concepts don't cover. -
undefined-behavior.md 5.5 KB
# Undefined behavior — catalog, sanitizers, fixes UB is not "an error at runtime." The standard says the program has *no defined meaning*, which licenses the optimizer to assume the situation never happens and rewrite code on that basis. That is why UB produces distant, nonsensical crashes and "works in Debug, breaks in Release." You do not debug UB by reasoning about what the CPU *did*; you remove it by construction and prove its absence with sanitizers. Static analysis (clang-tidy, cppcheck) and dynamic sanitizers catch **disjoint** bug classes — run both. Sanitizers only see the paths your tests exercise, so coverage matters. ## The catalog | Class | What it is | Caught by | Fix | | --- | --- | --- | --- | | Lifetime / dangling | reference or pointer to a destroyed object (returned local, dangling iterator after `push_back`, view outliving its owner) | ASan (heap/stack-use-after-scope) | return by value; own with `unique_ptr`; never store a `string_view`/`span` past its backing's lifetime | | Use-after-move | reading an object after `std::move` (valid but unspecified state) | clang-tidy (`bugprone-use-after-move`) — **not** ASan | reassign before reading, or don't read it | | Out-of-bounds | index/iterator past the end of a container or array | ASan | `.at()` or a bounds-checked view; range-for / ranges; never trust an external index | | Signed integer overflow | `INT_MAX + 1`, etc. (UB; unsigned wraps, signed does not) | UBSan | use a wider type, check before, or `<numeric>`/`ckd_add` (C++26) overflow-checked ops | | Strict aliasing | reading an object through an unrelated pointer type | UBSan (partial); compiler `-Wstrict-aliasing` | `std::bit_cast` (C++20) or `memcpy`, never a reinterpret_cast pun | | Uninitialized read | reading a variable before assigning it | UBSan (MemorySanitizer for full coverage) | always initialize (`int n{};`); enable `-Wuninitialized` | | Data race | two threads access the same memory, one writes, no synchronization | TSan | a mutex/`scoped_lock`, `atomic<T>`, or don't share mutable state | | Null / misaligned deref | dereferencing `nullptr` or a misaligned pointer | UBSan | check before deref; references can't be null — prefer them | | Invalid downcast / enum | `static_cast` to the wrong dynamic type; out-of-range enum value | UBSan (`vptr`, `enum`) | `dynamic_cast` when polymorphic; validate enum inputs | ## Sanitizer flag combinations & caveats - **ASan + UBSan together:** `-fsanitize=address,undefined -fno-omit-frame-pointer -g`. This is the everyday build for tests and the local gate. Add `-fsanitize=integer` (Clang) to extend UBSan to unsigned wraparound you care about. - **TSan alone:** `-fsanitize=thread -g`. It is **incompatible** with ASan — never combine them. Run it as a separate build/CI job over your concurrent tests. - **MemorySanitizer** (Clang) for uninitialized reads needs *all* code (including libc++) instrumented; usually overkill — `-Wuninitialized` + always-initialize covers most cases. - Sanitizers slow execution ~2–10x and need `-g` and frame pointers for readable stacks. They are a test/CI tool, not a production build. - Tune at runtime via env: `ASAN_OPTIONS=detect_leaks=1:abort_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`. ## Worked fixes ```cpp // Dangling reference (ASan: stack-use-after-return). const std::string& bad() { std::string s = make(); return s; } // s dies at the brace std::string good() { return make(); } // by value; RVO elides the copy // Iterator invalidation (ASan: heap-use-after-free). for (auto it = v.begin(); it != v.end(); ++it) if (*it == x) v.push_back(*it); // Bad: push_back may realloc, it now dangles auto n = std::ranges::count(v, x); // Good: compute first, then mutate // Signed overflow (UBSan: signed-integer-overflow). int total = a + b; // Bad if a+b > INT_MAX auto total = std::int64_t{a} + b; // Good: widen before the add // Strict aliasing (type pun). float f = *reinterpret_cast<float*>(&i); // Bad: UB auto f = std::bit_cast<float>(i); // Good: C++20, defined ``` ## Reading an ASan report A typical use-after-free report has three stacks — read them bottom-up by *event*: ``` ==12345==ERROR: AddressSanitizer: heap-use-after-free on address 0x602... READ of size 4 at 0x602... thread T0 #0 0x... in Cache::get(int) src/cache.cpp:42 <- where the bad access happened ... 0x602... is located 0 bytes inside of 4-byte region [0x602..,0x602..) freed by thread T0 here: <- who freed it (the delete/dtor) #0 0x... operator delete(void*) #1 0x... in Cache::evict(int) src/cache.cpp:31 previously allocated by thread T0 here: <- who allocated it #0 0x... operator new(unsigned long) #1 0x... in Cache::put(int,int) src/cache.cpp:18 ``` Procedure: (1) the top READ/WRITE frame is the *symptom* line; (2) "freed by" is the line that ended the object's life too early; (3) "previously allocated" is its birth. The bug is almost always that the "freed by" path runs while a pointer/reference/iterator captured between allocation and the symptom is still in use. The fix is an ownership fix — usually replacing the raw owning pointer with a `unique_ptr`/`shared_ptr` so the lifetime can't be cut short, or extending the owner's scope. For data races, TSan prints the two conflicting accesses (read/write) with both stacks and the thread that created each; the fix is a single mutex/`scoped_lock` or an `atomic<T>` guarding that memory.
-
-
scripts
-
verify.sh 5.8 KB
#!/usr/bin/env bash # # verify.sh - local quality gate for a CMake C++ project (superset of CI). # # Usage: # cd <your-project-root> # the directory containing CMakeLists.txt # ./verify.sh # # Runs: clang-format (dry-run), a CMake configure+build with warnings-as-errors and # ASan+UBSan, the test target via ctest, and optional clang-tidy + cppcheck. # Tools that are not installed are skipped with a yellow warning (not a failure). # Real problems (format drift, build failure, sanitizer abort, test failure) exit non-zero. # Read-only: never mutates your source. Only writes under build/verify/. # # Portability: runs on stock macOS bash 3.2 (no mapfile, no associative arrays, # no unguarded array expansions under `set -u`). set -euo pipefail # Colors only when stdout is a TTY (keeps logs/CI output clean). if [ -t 1 ]; then YELLOW=$'\033[33m'; RED=$'\033[31m'; GREEN=$'\033[32m'; RESET=$'\033[0m' else YELLOW=''; RED=''; GREEN=''; RESET='' fi failed=0 BUILD_DIR="build/verify" have() { command -v "$1" >/dev/null 2>&1; } warn() { printf '%s[skip]%s %s\n' "$YELLOW" "$RESET" "$*"; } fail() { printf '%s[fail]%s %s\n' "$RED" "$RESET" "$*"; failed=1; } ok() { printf '%s[ ok ]%s %s\n' "$GREEN" "$RESET" "$*"; } info() { printf -- '----- %s\n' "$*"; } # Must run from a CMake project root. if [ ! -f CMakeLists.txt ]; then printf '%serror:%s no CMakeLists.txt in %s - cd into your project root first.\n' \ "$RED" "$RESET" "$(pwd)" >&2 exit 2 fi # Collect tracked C/C++ sources (git if available, else find). Read-only. collect_sources() { if have git && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then git ls-files '*.cpp' '*.cc' '*.cxx' '*.hpp' '*.hh' '*.hxx' '*.h' '*.ixx' 2>/dev/null else find . -path ./"$BUILD_DIR" -prune -o -type f \ \( -name '*.cpp' -o -name '*.cc' -o -name '*.cxx' \ -o -name '*.hpp' -o -name '*.hh' -o -name '*.hxx' \ -o -name '*.h' -o -name '*.ixx' \) -print 2>/dev/null fi } # 1. clang-format - dry-run, never rewrites. Empty source set is a clean pass. info "clang-format" if have clang-format; then srcs="$(collect_sources)" if [ -z "$srcs" ]; then ok "no C/C++ sources to format" else fmt_failed=0 # -Werror + --dry-run makes clang-format exit non-zero on any drift, printing nothing else. printf '%s\n' "$srcs" | while IFS= read -r f; do [ -n "$f" ] || continue clang-format --dry-run -Werror "$f" >/dev/null 2>&1 || printf '%s\n' "$f" done > "${TMPDIR:-/tmp}/cpp_verify_fmt.$$" || true if [ -s "${TMPDIR:-/tmp}/cpp_verify_fmt.$$" ]; then fmt_failed=1 fail "files need formatting (run: clang-format -i <file>):" cat "${TMPDIR:-/tmp}/cpp_verify_fmt.$$" fi rm -f "${TMPDIR:-/tmp}/cpp_verify_fmt.$$" [ "$fmt_failed" -eq 0 ] && ok "clang-format clean" fi else warn "clang-format not found (https://clang.llvm.org/docs/ClangFormat.html)" fi # 2-4. CMake configure + build under warnings-as-errors + ASan+UBSan, then ctest. info "cmake configure (ASan+UBSan, warnings-as-errors)" if have cmake; then SAN_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -g -Werror" if cmake -S . -B "$BUILD_DIR" \ -DCMAKE_BUILD_TYPE=Debug \ -DCMAKE_CXX_FLAGS="$SAN_FLAGS" \ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON >/dev/null 2>&1; then ok "configured ($BUILD_DIR)" info "cmake build" if cmake --build "$BUILD_DIR" >/dev/null 2>&1; then ok "build clean (warnings-as-errors)" info "ctest" if have ctest; then # ctest exits non-zero with "No tests were found" when there are none; treat that as a skip. ctest_out="$(ctest --test-dir "$BUILD_DIR" --output-on-failure 2>&1 || true)" if printf '%s' "$ctest_out" | grep -qi 'no tests were found'; then warn "no tests registered with ctest" elif printf '%s' "$ctest_out" | grep -qiE 'tests failed|failed out of|errors? while'; then fail "ctest reported failures" printf '%s\n' "$ctest_out" else ok "tests pass (ASan+UBSan)" fi else warn "ctest not found (ships with CMake)" fi else fail "build failed (warnings-as-errors / sanitizer compile error)" fi else fail "cmake configure failed" fi else warn "cmake not found - cannot build/test (https://cmake.org/download/)" fi # 5. clang-tidy - optional; reads compile_commands.json from the build dir. info "clang-tidy" if have clang-tidy && [ -f "$BUILD_DIR/compile_commands.json" ]; then srcs="$(collect_sources | grep -E '\.(cpp|cc|cxx)$' || true)" if [ -z "$srcs" ]; then warn "no translation units for clang-tidy" else tidy_failed=0 printf '%s\n' "$srcs" | while IFS= read -r f; do [ -n "$f" ] || continue clang-tidy -p "$BUILD_DIR" "$f" >/dev/null 2>&1 || printf '%s\n' "$f" done > "${TMPDIR:-/tmp}/cpp_verify_tidy.$$" || true if [ -s "${TMPDIR:-/tmp}/cpp_verify_tidy.$$" ]; then tidy_failed=1 fail "clang-tidy reported issues in:" cat "${TMPDIR:-/tmp}/cpp_verify_tidy.$$" fi rm -f "${TMPDIR:-/tmp}/cpp_verify_tidy.$$" [ "$tidy_failed" -eq 0 ] && ok "clang-tidy clean" fi else warn "clang-tidy not found or no compile_commands.json (optional)" fi # 6. cppcheck - optional static analysis. info "cppcheck" if have cppcheck; then if [ -f "$BUILD_DIR/compile_commands.json" ]; then if cppcheck --enable=warning,performance --error-exitcode=1 \ --project="$BUILD_DIR/compile_commands.json" >/dev/null 2>&1; then ok "cppcheck clean" else fail "cppcheck reported issues" fi else warn "cppcheck: no compile_commands.json to analyze" fi else warn "cppcheck not found (optional)" fi echo if [ "$failed" -ne 0 ]; then printf '%sFAIL:%s one or more checks failed.\n' "$RED" "$RESET" exit 1 fi printf '%sPASS:%s all checks passed.\n' "$GREEN" "$RESET"
-
-
SKILL.md 15.5 KB
--- name: cpp description: "Use when writing, reviewing, modernizing, building, or debugging C++ - RAII and resource lifetime, smart-pointer ownership, move semantics and the Rule of Zero/Five, target-based CMake with FetchContent, and killing undefined behavior with ASan/UBSan/TSan plus clang-tidy. NOT borrow-checker / Result-Option / cargo memory safety (that is rust)." tags: [cpp, c++, modern-cpp, raii, cmake] recommends: [rust, secure-coding, deployment] origin: risco --- # Modern C++ Write, review, modernize, build, and debug C++ the way the C++ Core Guidelines intend: RAII for every resource, ownership made explicit through smart pointers and values, no undefined behavior by construction, and a target-based CMake build proven clean under sanitizers. Targets **C++20/23** for production today. C++23 is ISO/IEC 14882:2024; WG21 froze C++26's technical content on **2026-03-28** (ISO publication follows) — adopt C++26 features only behind confirmed compiler support. Compiler matrix: | Compiler | C++23 | C++26 | Flag | | --- | --- | --- | --- | | GCC | since 11 | since 14 (GCC 16.1 covers most of C++26) | `-std=c++23` / `-std=c++26` | | Clang | 13–18 progressively | in progress (Clang 23 dev) | `-std=c++23` / `-std=c++2c` | | MSVC | latest | partial | `/std:c++23` / `/std:c++latest` | Delegate: borrow-checker, `Result`/`Option`, cargo, ownership-via-compiler -> [`rust`](../rust/SKILL.md) — C++ buys safety with discipline (RAII + smart pointers + sanitizers); do not conflate the mechanisms. Language-agnostic threat modeling, authz, OWASP-class review -> [`secure-coding`](../secure-coding/SKILL.md); the C++-specific memory/UB controls (bounds, lifetime, integer overflow, format-string, sanitizers) stay **here**. Containerizing and shipping the binary -> [`deployment`](../deployment/SKILL.md); this skill stops at the CMake build + a sanitizer-CI note. ## Decision rules Apply these on every C++ edit: 1. **Rule of Zero first.** Manage resources with members that already do it (`vector`, `string`, `unique_ptr`); write no destructor/copy/move at all. Why: hand-written special members are the #1 source of leaks and double-frees. 2. **Value by default.** Pass and return by value for small/copyable types; reach for the heap only when you need polymorphism, shared lifetime, or a large/stable address. Why: values can't dangle. 3. **Name the owner.** Exactly one type owns each resource; everyone else borrows. Why: ambiguous ownership is how use-after-free is born. 4. **`make_unique`/`make_shared`, never `new`.** So no naked owning pointer ever exists. 5. **Never an owning raw pointer.** Raw pointers/references are non-owning borrows only. 6. **Borrow with `span` / `string_view` / `const T&`.** Pass a view, not a copy or an owner, for read access. Why: zero-copy, and the callee provably can't free what it doesn't own. 7. **`const` and `constexpr` by default.** Why: the compiler enforces what you don't mutate and moves work off the hot path. 8. **No UB by construction.** No use-after-move, OOB index, signed overflow, uninitialized read, or data race. 9. **Sanitizers + warnings-as-errors in CI.** Build and test under `-fsanitize=address,undefined` with `-Werror`. 10. **Target-based CMake only.** `target_link_libraries` / `target_compile_features`, never directory-level `include_directories`/`link_libraries`. Why: directory commands leak flags globally and break composition. ## Ownership & smart pointers Pick the type from the *need*, not from habit: | Need | Use | | --- | --- | | Exclusive owner, one place frees it | `std::unique_ptr<T>` | | Genuinely shared lifetime (multiple owners, last one frees) | `std::shared_ptr<T>` | | Observe / break a `shared_ptr` cycle, no ownership | `std::weak_ptr<T>` (`.lock()` to use) | | Read-only borrow of contiguous range / string | `std::span<const T>` / `std::string_view` | | Borrow a single object, non-owning | `const T&` / `T&` / `T*` (never owning) | | Small, copyable, value-like | the value itself — no heap | Default to `unique_ptr`; only escalate to `shared_ptr` when ownership is *actually* shared, and prove the shared case isn't a disguised single owner first — `shared_ptr` is not "the safe default." ```cpp // Bad: naked owning pointer; leaks on the throw, double-frees if you copy the handle. Widget* w = new Widget(cfg); configure(w); // if this throws, w leaks delete w; // Good: ownership is the type; freed exactly once, exception-safe, no delete to forget. auto w = std::make_unique<Widget>(cfg); configure(*w); ``` ```cpp // Bad: parent <-> child shared_ptr cycle -> neither refcount hits zero -> leak forever. struct Node { std::shared_ptr<Node> parent, child; }; // Good: child owns down, parent observes up. Cycle broken; lock() before use. struct Node { std::shared_ptr<Node> child; // owns std::weak_ptr<Node> parent; // observes }; if (auto p = node.parent.lock()) { /* p is a valid shared_ptr here */ } ``` When an object must hand out a `shared_ptr` to itself, derive from `std::enable_shared_from_this<T>` and call `shared_from_this()` — never wrap `this` in a fresh `shared_ptr` (that creates a second, independent refcount and a guaranteed double-free). Deeper ownership/move reasoning -> `references/move-and-templates.md`. ## RAII Tie every resource — heap memory, file, socket, mutex, OS handle — to an object's lifetime; the destructor releases it. Why: cleanup then happens on *every* exit path (return, exception, break) for free, with no GC and no `finally`. Use the standard guards before writing your own: ```cpp std::lock_guard lock(mtx_); // locks now, unlocks at scope end (C++17 CTAD) std::scoped_lock locks(a_mtx, b_mtx); // multiple mutexes, deadlock-free acquisition std::unique_lock lk(mtx_); // movable / deferrable, for condition_variable std::ifstream in("data.txt"); // closes in its destructor ``` When you wrap a C resource yourself, make the destructor release and disable copies (Rule of Five or `unique_ptr` with a custom deleter): ```cpp // RAII wrapper for a FILE*: closes once, can't leak, can't double-close. class File { public: explicit File(const char* path, const char* mode) : f_(std::fopen(path, mode)) { if (!f_) throw std::runtime_error("open failed"); } ~File() { if (f_) std::fclose(f_); } File(const File&) = delete; // not copyable File& operator=(const File&) = delete; File(File&& o) noexcept : f_(std::exchange(o.f_, nullptr)) {} // move = steal File& operator=(File&& o) noexcept { std::swap(f_, o.f_); return *this; } FILE* get() const noexcept { return f_; } private: FILE* f_{}; }; // Even simpler when a deleter suffices — let unique_ptr own it (Rule of Zero): auto fp = std::unique_ptr<FILE, decltype(&std::fclose)>(std::fopen("d", "r"), &std::fclose); ``` ## Move semantics & Rule of Zero/Five Every expression is an *lvalue* (has a name, persists) or an *rvalue* (a temporary, about to die). `std::move` does not move anything — it casts an lvalue to an rvalue so a move constructor/assignment can *steal* its guts instead of copying. After you move from an object, it is valid but unspecified: only assign to it or destroy it; reading it is **use-after-move** (a real bug ASan/UBSan won't catch — clang-tidy will). - **Rule of Zero** (default): manage nothing by hand; let the compiler generate all five special members. This is correct for the vast majority of types. - **Rule of Five**: the moment you write *one* of destructor / copy-ctor / copy-assign / move-ctor / move-assign, you must reason about all five. If you're writing them, you probably should have used a `unique_ptr`/`vector` member and gone back to Rule of Zero. - **Move ops must be `noexcept`.** Why: `std::vector` reallocation only *moves* elements instead of copying them when the move is `noexcept` — otherwise it silently falls back to copies for the strong exception guarantee. ```cpp std::vector<std::string> v; v.push_back(std::move(name)); // transfers the buffer; `name` is now empty-but-valid // Bad: use-after-move — `name` holds an unspecified state here. log(name); // don't. Reassign name first, or just don't read it. ``` Return local objects by value and let **RVO / copy elision** remove the copy — do *not* `return std::move(local)`, which pessimizes by blocking elision. Take a forwarding reference `T&&` plus `std::forward<T>(x)` only in generic code that must preserve value category. Worked Rule-of-Five, perfect forwarding, CTAD, and C++20 concepts -> `references/move-and-templates.md`. ## Avoiding UB (essentials) Undefined behavior is the compiler's permission to assume the bug can't happen and optimize on that assumption — so the symptom is often a *distant* crash or a "works in Debug, breaks in Release." Pair static analysis (clang-tidy, cppcheck) with dynamic sanitizers; they catch disjoint bug classes. | Sanitizer | Flag | Catches | | --- | --- | --- | | AddressSanitizer | `-fsanitize=address` | use-after-free, heap/stack buffer overflow, double-free | | UndefinedBehaviorSanitizer | `-fsanitize=undefined` | signed overflow, null/misaligned deref, bad shifts, invalid enum | | ThreadSanitizer | `-fsanitize=thread` | data races | Combine **ASan + UBSan** in one build (`-fsanitize=address,undefined`); run **TSan alone** (it's incompatible with ASan). Always add `-fno-omit-frame-pointer -g` for readable reports. ```cpp // Bad: returns a dangling reference into a destroyed temporary -> use-after-free, ASan fires. const std::string& name() { std::string s = build(); return s; } // s dies at return // Good: return by value; RVO makes it free. std::string name() { return build(); } ``` The full catalog (lifetime, OOB, signed overflow, strict-aliasing, uninitialized, data races, use-after-move), which sanitizer surfaces each, the canonical fix, and a "reading an ASan report" walkthrough -> `references/undefined-behavior.md`. ## Modern CMake (essentials) Target-based only. State requirements on the *target*, never globally: ```cmake cmake_minimum_required(VERSION 3.21) project(app LANGUAGES CXX) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) # feeds clang-tidy / clangd include(FetchContent) # FetchContent ships with CMake since 3.11 FetchContent_Declare(Catch2 GIT_REPOSITORY https://github.com/catchorg/Catch2.git GIT_TAG v3.7.1) FetchContent_MakeAvailable(Catch2) # its targets work just like find_package targets add_executable(app src/main.cpp) target_compile_features(app PRIVATE cxx_std_23) # request the standard on the target target_compile_options(app PRIVATE -Wall -Wextra -Wpedantic -Werror) target_link_libraries(app PRIVATE Catch2::Catch2WithMain) ``` Full template (src/include/tests layout, `CMakePresets.json` with debug/asan/release presets, fmt + GoogleTest via FetchContent, per-compiler warning + sanitizer flags, install/export) -> `references/cmake.md`. ## Standard-library idioms Reach for the library before hand-rolling: ```cpp #include <algorithm> #include <ranges> #include <expected> // C++23 #include <format> // C++20 // Ranges over raw index loops — no off-by-one, no manual bounds. auto evens = nums | std::views::filter([](int n){ return n % 2 == 0; }); std::ranges::sort(v); // std::expected (C++23) over out-params / sentinel returns / exceptions for expected failure. std::expected<Config, std::string> load(std::string_view path); if (auto cfg = load(p)) use(*cfg); else log(cfg.error()); std::optional<User> find(int id); // "maybe absent", not a magic -1 / nullptr std::span<const int> view(v); // borrow a contiguous range, no copy, no owner auto [it, inserted] = m.try_emplace(k, val); // structured bindings enum class Color { Red, Green }; // scoped, no implicit int conversions std::string msg = std::format("{} of {}", i, n); // type-safe, no printf format-string UB ``` Prefer `at()` or a range-checked view when the index isn't provably in bounds; `operator[]` on a bad index is UB, not an exception. ## Testing & tooling - **Tests:** Catch2 or GoogleTest pulled via `FetchContent` (above); run them with `ctest`. - **Static analysis:** `clang-tidy -p build` (reads `compile_commands.json`) and `cppcheck` — they catch use-after-move, missing `noexcept`, and lifetime bugs the compiler won't. - **Dynamic analysis:** run the test target under ASan+UBSan so tests *prove* no UB on covered paths. - **Format:** `clang-format -i` with a checked-in `.clang-format`. - **Local gate:** `./scripts/verify.sh` from the project root runs format + an ASan/UBSan, warnings-as-errors build + `ctest` + optional tidy/cppcheck. Missing tools are skipped, not failed. ## Anti-patterns | Rationalization | Reality / Do instead | | --- | --- | | "I'll just `new`/`delete` carefully" | One early return or throw and you leak/double-free. `make_unique`, always. | | "A raw owning pointer is faster" | `unique_ptr` is zero-overhead; the cost is imaginary, the leak is real. | | "`shared_ptr` everywhere is the safe default" | Shared ownership invites cycles + atomic refcount cost. Default `unique_ptr`; share only when truly shared. | | "The C-style cast is fine, I know the type" | Use `static_cast`/`dynamic_cast`; C casts silently reinterpret and hide bugs. | | "Skip `noexcept` on the move ctor" | `vector` then copies instead of moving on realloc. Mark moves `noexcept`. | | "UB won't happen on my compiler" | UB lets the optimizer delete your checks; "works in Debug" proves nothing. | | "No sanitizers, it ran fine" | It ran; it wasn't *correct*. Build+test under ASan+UBSan. | | "A hand-rolled Makefile is simpler" | It rots and leaks flags. Target-based CMake is the contract. | | "`v[i]` is in range, I checked" | If it's not provable, use `.at()` or a checked view; OOB is UB. | | "`return std::move(local)` to be fast" | It blocks RVO and is slower. Return the local by value. | | "`using namespace std;` in a header" | Pollutes every includer; ODR/ambiguity bugs. Never in a header. | | "An out-param instead of returning the value" | Return by value (RVO) or `optional`/`expected`; out-params hide aliasing and UB. | | "A global / singleton is simpler" | It's hidden shared mutable state -> data races + untestable. Inject it. | ## Quick reference | Task | Command / idiom | | --- | --- | | Configure + build | `cmake -S . -B build && cmake --build build` | | Configure with sanitizers | `cmake -S . -B build -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -g"` | | Test | `ctest --test-dir build --output-on-failure` | | ASan + UBSan | `-fsanitize=address,undefined -fno-omit-frame-pointer -g` | | ThreadSanitizer (alone) | `-fsanitize=thread -g` | | Format | `clang-format -i src/*.cpp` | | Static analysis | `clang-tidy -p build src/*.cpp` · `cppcheck --enable=warning src/` | | Std flag | GCC/Clang `-std=c++23` (C++26: GCC `-std=c++26`, Clang `-std=c++2c`), MSVC `/std:c++23` | | Local gate | `./scripts/verify.sh` (run in your project root) | ## Project grounding (02-DOCS) In a project with a `02-DOCS/` layer (the [`harness`](../harness/SKILL.md) Karpathy wiki), read `02-DOCS/wiki/stack/cpp.md` first and stay consistent with it. If it is missing or stale, write this project's real choices there — std version and compiler matrix, CMake layout and presets, the sanitizer/warning policy, the ownership/error conventions — index it in `02-DOCS/wiki/index.md` (the Knowledge map; root `CLAUDE.md` keeps only a pointer to it), and bump its `Updated` date in the same change as any convention change. No `02-DOCS/` layer? Skip silently (optionally suggest `harness`). Conventions are *recorded, not gated* — never block the task on this.
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.