Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计通过

cpp-guide.cpp 指南

Agent Skill

cpp-guide 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

188

周安装

8

GitHub Stars

8

下载量

66
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:cpp-guide(.cpp 指南)
来源仓库:https://github.com/ar4mirez/samuel
仓库路径:skills/cpp-guide
安装命令:
npx skills add https://github.com/ar4mirez/samuel --skill cpp-guide
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/ar4mirez/samuel --skill cpp-guide

简介

cpp-guide 提供 C/C++ 现代编程范式参考,强调 RAII、零原始所有权和编译期优化。

  • 适用于跨平台开发、系统编程和高性能计算,支持 constexpr 和概念约束。
  • 警告视为错误,依赖静态断言和类型系统捕获逻辑错误,减少运行时失败。
  • 建议与团队编码规范对齐,统一资源管理和异常处理策略,提升代码一致性。
  • cpp-guide 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

C/C++ Guide

Applies to: C++20, Systems Programming, Embedded, Game Engines, High-Performance Computing

Core Principles

  1. RAII Everywhere: Every resource (memory, files, locks, sockets) is owned by an object whose destructor releases it
  2. Zero Raw Ownership: Never use new/delete directly; use smart pointers and containers for all heap allocation
  3. Value Semantics by Default: Pass and return by value; rely on move semantics and copy elision for performance
  4. Compile-Time over Run-Time: Use constexpr, static_assert, concepts, and templates to catch errors at compile time
  5. Warnings Are Errors: Build with -Wall -Wextra -Wpedantic -Werror; every warning is a latent bug

Guardrails

Standard & Compiler

  • Use C++20 as the minimum standard (-std=c++20 / CMAKE_CXX_STANDARD 20)
  • Compile with at least -Wall -Wextra -Wpedantic; treat warnings as errors (-Werror)
  • Enable sanitizers in debug builds: -fsanitize=address,undefined
  • Use static_assert to verify assumptions about types, sizes, and alignments
  • Set CMAKE_EXPORT_COMPILE_COMMANDS ON for clang-tidy and IDE integration
  • Pin compiler minimum version in CI (e.g., GCC 12+, Clang 15+, MSVC 19.34+)

Code Style

  • Run clang-format before every commit (no exceptions)
  • Run clang-tidy with project checks before every commit
  • snake_case for functions, variables, namespaces, file names
  • PascalCase for types (classes, structs, enums, concepts, type aliases)
  • SCREAMING_SNAKE_CASE for macros and compile-time constants
  • Prefer enum class over plain enum (scoped, no implicit conversion)
  • Header include order: own header, project headers, third-party, standard library
  • Use #pragma once or traditional include guards consistently (pick one)
  • No using namespace std; in headers (allowed in .cpp function scope only)

Memory Management

  • Default to stack allocation; heap allocate only when lifetime or size requires it
  • std::unique_ptr for single ownership (default smart pointer)
  • std::shared_ptr only when ownership is genuinely shared; document why
  • Use std::make_unique and std::make_shared (exception-safe, single allocation)
  • Containers (std::vector, std::string, std::array) manage their own memory
  • Use std::span for non-owning views into contiguous memory
  • Use std::string_view for non-owning string references (read-only, no allocation)

Error Handling

  • Use exceptions for truly exceptional conditions (constructor failure, precondition violations)
  • Use std::optional<T> for values that may be absent (replaces sentinel values)
  • Use std::variant<T, Error> or std::expected<T, E> (C++23) for result types
  • Mark functions noexcept when they do not throw (enables move optimization)
  • Always catch by const reference: catch (const std::exception& e)
  • Never catch ... without rethrowing or logging (swallowed errors are bugs)

Concurrency

  • Prefer std::jthread over std::thread (automatic join, stop token support)
  • Protect shared mutable state with std::mutex and std::scoped_lock
  • Use std::atomic for lock-free shared counters and flags
  • Never hold a lock while calling a callback or virtual function (deadlock risk)
  • All concurrent code must pass ThreadSanitizer (-fsanitize=thread)
  • Prefer std::latch, std::barrier, std::counting_semaphore (C++20) for coordination

Project Structure

myproject/
├── CMakeLists.txt              # Root: project(), options, add_subdirectory()
├── cmake/                      # Shared CMake modules (warnings, sanitizers)
├── src/
│   ├── CMakeLists.txt          # Library/executable targets
│   ├── main.cpp                # Entry point (thin: parse args, call run)
│   ├── app.cpp / app.hpp
│   └── domain/
│       └── user.cpp / user.hpp
├── include/myproject/          # Public headers (for libraries)
├── tests/
│   ├── CMakeLists.txt          # GoogleTest / Catch2 targets
│   └── test_user.cpp
├── benchmarks/
├── .clang-format
└── .clang-tidy
  • main.cpp should be thin: parse arguments, build config, call into library code
  • One class per header/source pair; test files mirror source structure
  • Use FetchContent or find_package for dependencies

CMakeLists.txt Essentials

cmake_minimum_required(VERSION 3.20)
project(myproject VERSION 0.1.0 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

add_compile_options(-Wall -Wextra -Wpedantic -Werror)

if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    add_compile_options(-fsanitize=address,undefined -fno-omit-frame-pointer)
    add_link_options(-fsanitize=address,undefined)
endif()

add_subdirectory(src)
add_subdirectory(tests)

Key Patterns

RAII Resource Wrapper

class FileHandle {
public:
    explicit FileHandle(const std::filesystem::path& path)
        : handle_(std::fopen(path.c_str(), "r")) {
        if (!handle_) {
            throw std::runtime_error("Failed to open: " + path.string());
        }
    }
    ~FileHandle() { if (handle_) std::fclose(handle_); }

    FileHandle(const FileHandle&) = delete;
    FileHandle& operator=(const FileHandle&) = delete;
    FileHandle(FileHandle&& other) noexcept : handle_(std::exchange(other.handle_, nullptr)) {}
    FileHandle& operator=(FileHandle&& other) noexcept {
        if (this != &other) { if (handle_) std::fclose(handle_); handle_ = std::exchange(other.handle_, nullptr); }
        return *this;
    }

    FILE* get() const noexcept { return handle_; }
private:
    FILE* handle_;
};

Smart Pointers

// unique_ptr: default choice, single ownership
auto user = std::make_unique<User>("alice", "alice@example.com");
process_user(*user);  // pass by reference, not pointer

// shared_ptr: only when ownership is genuinely shared
auto config = std::make_shared<Config>(load_config("app.toml"));
auto worker1 = std::jthread([config] { serve(config); });
auto worker2 = std::jthread([config] { monitor(config); });

// weak_ptr: break reference cycles, optional observation
class TreeNode {
    std::vector<std::shared_ptr<TreeNode>> children_;
    std::weak_ptr<TreeNode> parent_;  // non-owning back-reference
};

Move Semantics: Rule of Zero / Five

// Rule of Zero: prefer this. Let members manage resources.
struct UserRecord {
    std::string name;
    std::string email;
    std::vector<std::string> roles;
    // No special member functions needed -- std::string and std::vector handle everything.
};

// Rule of Five: only when managing a raw resource manually.
// See references/patterns.md for full RAII wrapper examples.
// Key rules: move constructors/assignment MUST be noexcept;
// use std::exchange to leave moved-from objects in a valid state.

std::optional and std::variant

// std::optional: replaces sentinel values (-1, nullptr, "")
std::optional<User> find_user(std::string_view email) {
    auto it = users_.find(std::string(email));
    if (it == users_.end()) return std::nullopt;
    return it->second;
}

if (auto user = find_user("alice@example.com")) {
    std::println("Found: {}", user->name);
}

// std::variant: type-safe tagged union
using ParseResult = std::variant<int, double, std::string>;

std::visit(overloaded{
    [](int v)                { std::println("int: {}", v); },
    [](double v)             { std::println("double: {}", v); },
    [](const std::string& v) { std::println("string: {}", v); },
}, result);

Concepts (C++20)

template<typename T>
concept Hashable = requires(T a) {
    { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;
};

template<Hashable Key, typename Value>
class Cache {
public:
    void put(const Key& key, Value value) { store_[key] = std::move(value); }
    std::optional<Value> get(const Key& key) const {
        auto it = store_.find(key);
        return it != store_.end() ? std::optional(it->second) : std::nullopt;
    }
private:
    std::unordered_map<Key, Value> store_;
};

constexpr Computation

constexpr int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}
static_assert(factorial(5) == 120);

consteval auto make_lookup_table() {
    std::array<int, 256> table{};
    for (int i = 0; i < 256; ++i) table[i] = (i * i) % 256;
    return table;
}
constexpr auto kLookup = make_lookup_table();

Ranges (C++20)

auto active_user_emails(const std::vector<User>& users) {
    return users
        | std::views::filter([](const User& u) { return u.is_active; })
        | std::views::transform(&User::email);
}

auto top_scores = scores
    | std::views::filter([](int s) { return s > 0; })
    | std::views::transform([](int s) { return s * 100 / max_score; })
    | std::views::take(10);

Structured Bindings

for (const auto& [key, value] : config_map) {
    std::println("{} = {}", key, value);
}

auto [min_it, max_it] = std::minmax_element(data.begin(), data.end());

auto [ok, msg, code] = process_request(req);
if (!ok) { log_error(msg, code); }

Testing

GoogleTest

class UserServiceTest : public ::testing::Test {
protected:
    void SetUp() override {
        db_ = std::make_unique<InMemoryDatabase>();
        service_ = std::make_unique<UserService>(*db_);
    }
    std::unique_ptr<InMemoryDatabase> db_;
    std::unique_ptr<UserService> service_;
};

TEST_F(UserServiceTest, CreateUserSucceeds) {
    auto user = service_->create_user("alice", "alice@example.com");
    EXPECT_EQ(user.name, "alice");
    EXPECT_EQ(user.email, "alice@example.com");
    EXPECT_FALSE(user.id.empty());
}

TEST_F(UserServiceTest, DuplicateEmailThrows) {
    service_->create_user("alice", "alice@example.com");
    EXPECT_THROW(service_->create_user("bob", "alice@example.com"), DuplicateEmailError);
}

Catch2

TEST_CASE("Parser handles valid input", "[parser]") {
    Parser parser;
    SECTION("integer literals") {
        auto result = parser.parse("42");
        REQUIRE(result.has_value());
        CHECK(std::get<int>(*result) == 42);
    }
    SECTION("empty input returns nullopt") {
        CHECK_FALSE(parser.parse("").has_value());
    }
}

Testing Standards

  • Test names describe behavior: TEST(OrderService, CancelledOrderCannotBeShipped)
  • Use TEST_F with fixtures for shared setup/teardown
  • EXPECT_* for non-fatal assertions; ASSERT_* only when continuation is meaningless
  • Coverage target: >80% for libraries, >60% for applications
  • Mock external dependencies with interfaces and dependency injection
  • Run tests under AddressSanitizer and UndefinedBehaviorSanitizer in CI

Tooling

Essential Commands

cmake -B build -DCMAKE_BUILD_TYPE=Debug    # Configure
cmake --build build -j$(nproc)             # Build (parallel)
cmake --build build --target test          # Run tests (CTest)
clang-format -i src/**/*.cpp src/**/*.hpp  # Format
clang-tidy src/*.cpp -- -std=c++20         # Static analysis
gcovr --root . --html -o coverage.html     # Coverage report

clang-format Configuration

# .clang-format
BasedOnStyle: Google
IndentWidth: 4
ColumnLimit: 100
PointerAlignment: Left
SortIncludes: CaseInsensitive

clang-tidy Configuration

# .clang-tidy
Checks: >
  -*, bugprone-*, cert-*, cppcoreguidelines-*, misc-*,
  modernize-*, performance-*, readability-*,
  -modernize-use-trailing-return-type
WarningsAsErrors: '*'
HeaderFilterRegex: 'src/.*'

Sanitizers Reference

SanitizerFlagCatches
AddressSanitizer-fsanitize=addressBuffer overflow, use-after-free, leaks
UndefinedBehaviorSanitizer-fsanitize=undefinedSigned overflow, null deref, alignment
ThreadSanitizer-fsanitize=threadData races, deadlocks
MemorySanitizer-fsanitize=memoryUninitialized reads (Clang only)
  • ASan + UBSan run together; TSan and MSan must run separately
  • Always use -fno-omit-frame-pointer with sanitizers

References

For detailed patterns and examples, see:

External References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

33.9%
按下载量换算22

Claude

30.68%
按下载量换算20

Cursor

19.89%
按下载量换算13

Gemini CLI

8.97%
按下载量换算6

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills