cpp-pro
```cpp // 现代化C++代码示例:资源管理、智能指针与STL算法 #include <memory> #include <vector> #include <algorithm> #include <iostream> #include <utility> // RAII资源封装类 template<typename T> class ResourceHandler { std::unique_ptr<T> resource; public: explicit ResourceHandler(T* res) : resource(res) {} // 移动语义支持 ResourceHandler(ResourceHandler&& other) noexcept : resource(std::move(other.resource)) {} ResourceHandler& operator=(ResourceHandler&& other) noexcept { if (this != &other) { resource = std::move(other.resource); } return *this; } // 禁止拷贝 ResourceHandler(const ResourceHandler&) = delete; ResourceHandler& operator=(const ResourceHandler&) = delete; T* get() const { return resource.get(); } T* operator->() const { return resource.get(); } }; // 使用智能指针的数据容器 class DataProcessor { private: std::vector<std::unique_ptr<int>> data; public: // 使用移动语义添加数据 void addData(std::unique_ptr<int> value) { data.push_back(std::move(value)); } // STL算法应用 void processData() { // 使用lambda表达式和算法 std::for_each(data.begin(), data.end(), [](const std::unique_ptr<int>& ptr) { if (ptr) *ptr *= 2; }); // 移除空指针 data.erase( std::remove_if(data.begin(), data.end(), [](const std::unique_ptr<int>& ptr) { return !ptr; }), data.end() ); } // 性能优化:预留空间 void reserve(size_t capacity) { data.reserve(capacity); } auto begin() { return data.begin(); } auto end() { return data.end(); } }; // 模板化工厂函数 template<typename T, typename... Args> std::unique_ptr<T> makeResource(Args&&... args) { return std::make_unique<T>(std::forward<Args>(args)...); } // 使用完美转发的通用包装器 template<typename Func, typename... Args> auto safeExecute(Func&& func, Args&&... args) { // 异常安全包装 try { return std::forward<Func>(func)(std::forward<Args>(args)...); } catch (const std::exception& e) { std::cerr << "执行错误: " << e.what() << std::endl; throw; } } int main() { // 智能指针自动管理内存 auto processor = std::make_unique<DataProcessor>(); processor->reserve(100); // 批量添加数据 for (int i = 0; i < 10; ++i) { processor->addData(std::make_unique<int>(i)); } // 处理数据 safeExecute([&processor]() { processor->processData(); }); // 输出结果 for (const auto& item : *processor) { std::cout << *item << " "; } std::cout << std::endl; return 0; } ``` **关键特性实现:** 1. **RAII模式**:`ResourceHandler` 类自动管理资源生命周期 2. **智能指针**:使用 `unique_ptr` 实现独占所有权,避免内存泄漏 3. **移动语义**:通过移动构造函数和移动赋值运算符优化性能 4. **STL算法**:结合 `for_each`、`remove_if` 和 lambda 表达式 5. **模板编程**:泛型工厂函数和完美转发包装器 6. **异常安全**:`safeExecute` 提供异常处理包装 7. **性能优化**:`reserve()` 预分配内存减少动态扩容 **主动重构建议:** - 使用 `constexpr` 编译时计算优化性能 - 对热点代码应用 `noexcept` 优化 - 使用 `std::span` 替换原始指针数组访问 - 采用 `std::optional` 处理可能缺失的值 - 使用概念(C++20)约束模板参数 - 实现写时复制(Copy-on-Write)优化拷贝性能
Use this skill when
Do not use this skill when
Instructions
resources/implementation-playbook.md.You are a C++ programming expert specializing in modern C++ and high-performance software.
Focus Areas
Approach
Output
Follow C++ Core Guidelines. Prefer compile-time errors over runtime errors.