cpp

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

C++

C++

Modern C++ development with smart pointers, RAII, and performance optimization.
基于智能指针、RAII机制与性能优化的现代C++开发。

When to Use

适用场景

  • Working with
    .cpp
    or
    .hpp
    files
  • Systems programming and embedded
  • Game development with Unreal Engine
  • Performance-critical applications
  • 处理
    .cpp
    .hpp
    文件时
  • 系统编程与嵌入式开发
  • 使用Unreal Engine进行游戏开发
  • 性能关键型应用

Quick Start

快速开始

cpp
#include <memory>
#include <string>
#include <vector>

class User {
public:
    User(std::string name, std::string email)
        : name_(std::move(name)), email_(std::move(email)) {}

    const std::string& name() const { return name_; }
    const std::string& email() const { return email_; }

private:
    std::string name_;
    std::string email_;
};

auto user = std::make_unique<User>("John", "john@example.com");
cpp
#include <memory>
#include <string>
#include <vector>

class User {
public:
    User(std::string name, std::string email)
        : name_(std::move(name)), email_(std::move(email)) {}

    const std::string& name() const { return name_; }
    const std::string& email() const { return email_; }

private:
    std::string name_;
    std::string email_;
};

auto user = std::make_unique<User>("John", "john@example.com");

Core Concepts

核心概念

Smart Pointers

智能指针

cpp
// unique_ptr - exclusive ownership
auto user = std::make_unique<User>("John");

// shared_ptr - shared ownership
auto shared = std::make_shared<Resource>();
auto copy = shared;  // ref count increases

// weak_ptr - non-owning observer
std::weak_ptr<Resource> observer = shared;
if (auto locked = observer.lock()) {
    // safe to use
}

// Never use raw new/delete for ownership
cpp
// unique_ptr - exclusive ownership
auto user = std::make_unique<User>("John");

// shared_ptr - shared ownership
auto shared = std::make_shared<Resource>();
auto copy = shared;  // ref count increases

// weak_ptr - non-owning observer
std::weak_ptr<Resource> observer = shared;
if (auto locked = observer.lock()) {
    // safe to use
}

// Never use raw new/delete for ownership

Move Semantics

移动语义

cpp
class Buffer {
public:
    Buffer(size_t size) : data_(new char[size]), size_(size) {}

    // Move constructor
    Buffer(Buffer&& other) noexcept
        : data_(other.data_), size_(other.size_) {
        other.data_ = nullptr;
        other.size_ = 0;
    }

    // Move assignment
    Buffer& operator=(Buffer&& other) noexcept {
        if (this != &other) {
            delete[] data_;
            data_ = other.data_;
            size_ = other.size_;
            other.data_ = nullptr;
            other.size_ = 0;
        }
        return *this;
    }

    ~Buffer() { delete[] data_; }

private:
    char* data_;
    size_t size_;
};
cpp
class Buffer {
public:
    Buffer(size_t size) : data_(new char[size]), size_(size) {}

    // Move constructor
    Buffer(Buffer&& other) noexcept
        : data_(other.data_), size_(other.size_) {
        other.data_ = nullptr;
        other.size_ = 0;
    }

    // Move assignment
    Buffer& operator=(Buffer&& other) noexcept {
        if (this != &other) {
            delete[] data_;
            data_ = other.data_;
            size_ = other.size_;
            other.data_ = nullptr;
            other.size_ = 0;
        }
        return *this;
    }

    ~Buffer() { delete[] data_; }

private:
    char* data_;
    size_t size_;
};

Common Patterns

常见模式

Modern C++ Features

现代C++特性

cpp
// Structured bindings (C++17)
auto [name, age] = std::make_pair("John", 25);
for (const auto& [key, value] : map) { /* ... */ }

// std::optional (C++17)
std::optional<User> findUser(int id) {
    if (exists) return User{...};
    return std::nullopt;
}

// Concepts (C++20)
template<typename T>
concept Numeric = std::is_arithmetic_v<T>;

template<Numeric T>
T add(T a, T b) { return a + b; }

// Ranges (C++20)
auto result = numbers
    | std::views::filter([](int n) { return n % 2 == 0; })
    | std::views::transform([](int n) { return n * 2; });
cpp
// Structured bindings (C++17)
auto [name, age] = std::make_pair("John", 25);
for (const auto& [key, value] : map) { /* ... */ }

// std::optional (C++17)
std::optional<User> findUser(int id) {
    if (exists) return User{...};
    return std::nullopt;
}

// Concepts (C++20)
template<typename T>
concept Numeric = std::is_arithmetic_v<T>;

template<Numeric T>
T add(T a, T b) { return a + b; }

// Ranges (C++20)
auto result = numbers
    | std::views::filter([](int n) { return n % 2 == 0; })
    | std::views::transform([](int n) { return n * 2; });

RAII Pattern

RAII模式

cpp
class FileHandle {
public:
    explicit FileHandle(const char* path)
        : file_(std::fopen(path, "r")) {
        if (!file_) throw std::runtime_error("Cannot open file");
    }

    ~FileHandle() { if (file_) std::fclose(file_); }

    // Delete copy
    FileHandle(const FileHandle&) = delete;
    FileHandle& operator=(const FileHandle&) = delete;

    // Allow move
    FileHandle(FileHandle&& other) noexcept : file_(other.file_) {
        other.file_ = nullptr;
    }

private:
    FILE* file_;
};
cpp
class FileHandle {
public:
    explicit FileHandle(const char* path)
        : file_(std::fopen(path, "r")) {
        if (!file_) throw std::runtime_error("Cannot open file");
    }

    ~FileHandle() { if (file_) std::fclose(file_); }

    // Delete copy
    FileHandle(const FileHandle&) = delete;
    FileHandle& operator=(const FileHandle&) = delete;

    // Allow move
    FileHandle(FileHandle&& other) noexcept : file_(other.file_) {
        other.file_ = nullptr;
    }

private:
    FILE* file_;
};

Best Practices

最佳实践

Do:
  • Use smart pointers for ownership
  • Apply RAII for resource management
  • Use
    const
    and
    constexpr
    liberally
  • Prefer
    std::string_view
    for read-only strings
Don't:
  • Use raw
    new
    /
    delete
    for ownership
  • Return raw pointers from functions
  • Use C-style casts (use
    static_cast
    )
  • Ignore compiler warnings
建议:
  • 使用智能指针管理对象所有权
  • 应用RAII机制进行资源管理
  • 大量使用
    const
    constexpr
  • 对于只读字符串,优先使用
    std::string_view
避免:
  • 使用原生
    new
    /
    delete
    管理对象所有权
  • 从函数中返回原生指针
  • 使用C风格强制类型转换(应使用
    static_cast
  • 忽略编译器警告

Troubleshooting

问题排查

ErrorCauseSolution
Segmentation faultNull pointer or buffer overflowUse sanitizers, smart pointers
Memory leakMissing deleteUse RAII, smart pointers
Undefined behaviorDangling referenceEnsure lifetime validity
错误类型原因解决方案
Segmentation fault空指针或缓冲区溢出使用 sanitizers、智能指针
内存泄漏缺失delete操作使用RAII机制、智能指针
未定义行为悬垂引用确保对象生命周期有效性

References

参考资料