mcpField
C
cpp

cpp

github.com/htlin222开发78130 次安装4 周前更新
代码仓库

关于 cpp

cpp 是用于编写和维护现代 C++ 代码的技能,涵盖内存安全、模板、性能优化和旧代码现代化,并提供模式示例与实践建议。

主要功能

  1. 01智能指针与 RAII 指引
  2. 02STL 容器和算法实践
  3. 03C++20 concepts 与模板
  4. 04常见内存和并发问题修复

适用场景

  1. 01排查内存泄漏或悬空指针
  2. 02现代化旧版 C++ 代码
  3. 03优化代码并处理数据竞争

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/htlin222/dotfiles --skill cpp

安装后在 Claude Code 中输入/cpp确认已加载。

详细介绍

C++ 开发

编写安全、高性能的现代 C++ 代码。

适用场景

  • 编写 C++ 代码
  • 内存管理问题
  • 模板元编程
  • 性能优化
  • 现代化旧版 C++ 代码

现代 C++ 模式

智能指针
// Unique ownership
auto ptr = std::make_unique<Resource>();
process(std::move(ptr));

// Shared ownership
auto shared = std::make_shared<Resource>();
auto copy = shared;  // Reference count: 2

// Weak reference (no ownership)
std::weak_ptr<Resource> weak = shared;
if (auto locked = weak.lock()) {
    // Use locked
}
RAII
class FileHandle {
    FILE* handle_;
public:
    explicit FileHandle(const char* path)
        : handle_(fopen(path, "r")) {
        if (!handle_) throw std::runtime_error("Failed to open");
    }
    ~FileHandle() { if (handle_) fclose(handle_); }

    // Rule of 5
    FileHandle(const FileHandle&) = delete;
    FileHandle& operator=(const FileHandle&) = delete;
    FileHandle(FileHandle&& other) noexcept
        : handle_(std::exchange(other.handle_, nullptr)) {}
    FileHandle& operator=(FileHandle&& other) noexcept {
        std::swap(handle_, other.handle_);
        return *this;
    }
};
容器和算法
std::vector<int> nums = {3, 1, 4, 1, 5};

// Prefer algorithms over raw loops
std::sort(nums.begin(), nums.end());

auto it = std::find_if(nums.begin(), nums.end(),
    [](int n) { return n > 3; });

// Range-based for
for (const auto& num : nums) {
    std::cout << num << '\n';
}

// Structured bindings (C++17)
std::map<std::string, int> scores;
for (const auto& [name, score] : scores) {
    std::cout << name << ": " << score << '\n';
}
模板
// Concepts (C++20)
template<typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;

template<Numeric T>
T sum(const std::vector<T>& values) {
    return std::accumulate(values.begin(), values.end(), T{});
}

// SFINAE (pre-C++20)
template<typename T,
    typename = std::enable_if_t<std::is_arithmetic_v<T>>>
T multiply(T a, T b) { return a * b; }

最佳实践

  • 优先使用 const 和 constexpr
  • 使用智能指针,而非原始指针
  • 遵循 Rule of 0/5
  • 优先使用 STL 算法
  • 对只读字符串使用 std::string_view
  • 启用警告:-Wall -Wextra -Wpedantic

常见问题

问题症状修复
内存泄漏内存持续增长使用智能指针
悬垂指针崩溃/未定义行为检查生命周期
缓冲区溢出崩溃/安全问题使用 std::vector/span
数据竞争状态不一致mutex/atomic

示例

输入:“修复内存泄漏” **操作:**将原始指针替换为智能指针,确保使用 RAII

输入:“现代化这段 C++ 代码” **操作:**应用 C++17/20 特性,使用 STL,提升安全性

评论

支持 Markdown