cpp
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseC++ Development
现代C++开发
Write safe, performant modern C++ code.
编写安全、高性能的现代C++代码。
When to Use
适用场景
- Writing C++ code
- Memory management issues
- Template metaprogramming
- Performance optimization
- Legacy C++ modernization
- 编写C++代码
- 内存管理问题
- 模板元编程
- 性能优化
- 遗留C++代码现代化
Modern C++ Patterns
现代C++设计模式
Smart Pointers
智能指针
cpp
// 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
}cpp
// 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
RAII
cpp
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;
}
};cpp
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;
}
};Containers and Algorithms
容器与算法
cpp
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';
}cpp
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';
}Templates
模板
cpp
// 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; }cpp
// 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; }Best Practices
最佳实践
- Prefer and
constconstexpr - Use smart pointers over raw pointers
- Follow Rule of 0/5
- Prefer STL algorithms
- Use for read-only strings
std::string_view - Enable warnings:
-Wall -Wextra -Wpedantic
- 优先使用和
constconstexpr - 用智能指针替代裸指针
- 遵循Rule of 0/5规则
- 优先使用STL算法
- 对只读字符串使用
std::string_view - 启用警告:
-Wall -Wextra -Wpedantic
Common Issues
常见问题
| Issue | Symptom | Fix |
|---|---|---|
| Memory leak | Growing memory | Use smart pointers |
| Dangling ptr | Crash/UB | Check lifetime |
| Buffer overflow | Crash/security | Use std::vector/span |
| Data race | Inconsistent state | mutex/atomic |
| 问题 | 症状 | 修复方案 |
|---|---|---|
| 内存泄漏 | 内存持续增长 | 使用智能指针 |
| 悬垂指针 | 崩溃/未定义行为 | 检查对象生命周期 |
| 缓冲区溢出 | 崩溃/安全风险 | 使用std::vector/span |
| 数据竞争 | 状态不一致 | 使用mutex/atomic |
Examples
示例
Input: "Fix memory leak"
Action: Replace raw pointers with smart pointers, ensure RAII
Input: "Modernize this C++ code"
Action: Apply C++17/20 features, use STL, improve safety
输入: "修复内存泄漏"
操作: 用智能指针替换裸指针,确保遵循RAII原则
输入: "现代化这段C++代码"
操作: 应用C++17/20特性,使用STL,提升代码安全性