C++ RAII 资源管理:智能指针与作用域绑定
RAII(Resource Acquisition Is Initialization)是 C++ 核心设计模式,将资源生命周期与对象生命周期绑定。
1. 传统资源管理缺陷
void bad() {
int* p = new int[100];
// ... 可能抛出异常或提前返回
delete[] p; // 容易遗漏
}2. 智能指针
std::unique_ptr:独占所有权,不可拷贝,可移动。std::shared_ptr:引用计数,共享所有权。std::weak_ptr:打破循环引用。
#include <memory>
void good() {
auto p = std::make_unique<int[]>(100);
// 自动释放,无需显式 delete
}3. 自定义 RAII 类
class FileHandle {
FILE* f;
public:
FileHandle(const char* path) : f(fopen(path, "r")) {}
~FileHandle() { if (f) fclose(f); }
// 禁止拷贝,支持移动
};4. 作用域锁定(std::lock_guard)
std::mutex mtx;
void safe() {
std::lock_guard<std::mutex> lock(mtx);
// 自动解锁
}RAII 是现代 C++ 资源管理的基石,强烈推荐使用。
