C++开发Skill cpp

C++开发技能专注于使用现代C++特性如RAII、智能指针和STL来编写安全、高性能的代码。适用于C++编程、内存管理、模板元编程、性能优化和遗留代码现代化。关键词:C++开发、内存安全、性能优化、RAII、智能指针、STL、现代C++。

架构设计 0 次安装 0 次浏览 更新于 3/12/2026

名称: cpp 描述: 使用RAII、智能指针和STL编写现代C++代码。适用于C++开发、内存安全或性能优化。

C++ 开发

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

何时使用

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

现代C++模式

智能指针

// 唯一所有权
auto ptr = std::make_unique<Resource>();
process(std::move(ptr));

// 共享所有权
auto shared = std::make_shared<Resource>();
auto copy = shared;  // 引用计数: 2

// 弱引用(无所有权)
std::weak_ptr<Resource> weak = shared;
if (auto locked = weak.lock()) {
    // 使用 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_); }

    // 规则五
    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};

// 优先使用算法而非原始循环
std::sort(nums.begin(), nums.end());

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

// 基于范围的for循环
for (const auto& num : nums) {
    std::cout << num << '
';
}

// 结构化绑定(C++17)
std::map<std::string, int> scores;
for (const auto& [name, score] : scores) {
    std::cout << name << ": " << score << '
';
}

模板

// 概念(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(C++20之前)
template<typename T,
    typename = std::enable_if_t<std::is_arithmetic_v<T>>>
T multiply(T a, T b) { return a * b; }

最佳实践

  • 优先使用 constconstexpr
  • 使用智能指针而非原始指针
  • 遵循规则0/5
  • 优先使用STL算法
  • 使用 std::string_view 处理只读字符串
  • 启用警告:-Wall -Wextra -Wpedantic

常见问题

问题 症状 修复
内存泄漏 内存增长 使用智能指针
悬空指针 崩溃/未定义行为 检查生命周期
缓冲区溢出 崩溃/安全漏洞 使用 std::vector/span
数据竞争 状态不一致 互斥锁/原子操作

示例

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

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