Cpp 标志

Cpp

社区
ericrisco
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 borrow-checker / Result-Option / cargo memory safety (that is rust).

概览

发布者ericrisco
代码仓库rsc-harness
技能名称cpp
星标数
239
复刻数
24
附带文件
5
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 5 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 ericrisco 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Cpp AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/ericrisco/rsc-harness/tree/main/skills/cpp
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/ericrisco/rsc-harness.git /tmp/rsc-harness
mkdir -p .claude/skills
cp -r /tmp/rsc-harness/skills/cpp .claude/skills/cpp
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Cpp,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Cpp。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Cpp 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

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:

CompilerC++23C++26Flag
GCCsince 11since 14 (GCC 16.1 covers most of C++26)-std=c++23 / -std=c++26
Clang13–18 progressivelyin progress (Clang 23 dev)-std=c++23 / -std=c++2c
MSVClatestpartial/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:

  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:

NeedUse
Exclusive owner, one place frees itstd::unique_ptr<T>
Genuinely shared lifetime (multiple owners, last one frees)std::shared_ptr<T>
Observe / break a shared_ptr cycle, no ownershipstd::weak_ptr<T> (.lock() to use)
Read-only borrow of contiguous range / stringstd::span<const T> / std::string_view
Borrow a single object, non-owningconst T& / T& / T* (never owning)
Small, copyable, value-likethe 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.

SanitizerFlagCatches
AddressSanitizer-fsanitize=addressuse-after-free, heap/stack buffer overflow, double-free
UndefinedBehaviorSanitizer-fsanitize=undefinedsigned overflow, null/misaligned deref, bad shifts, invalid enum
ThreadSanitizer-fsanitize=threaddata 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

RationalizationReality / 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

TaskCommand / idiom
Configure + buildcmake -S . -B build && cmake --build build
Configure with sanitizerscmake -S . -B build -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -g"
Testctest --test-dir build --output-on-failure
ASan + UBSan-fsanitize=address,undefined -fno-omit-frame-pointer -g
ThreadSanitizer (alone)-fsanitize=thread -g
Formatclang-format -i src/*.cpp
Static analysisclang-tidy -p build src/*.cpp · cppcheck --enable=warning src/
Std flagGCC/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.

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Cpp AI 技能有什么作用?

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).

为什么在 TypingMind 中使用 Cpp?

因为您只需安装一次,就能搭配任何模型使用。Cpp 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Cpp?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/ericrisco/rsc-harness/tree/main/skills/cpp。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Cpp?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Cpp 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Cpp 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Cpp AI 技能免费吗?

是的。ericrisco 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇