C++资源管理之智能指针
在《Effective C++》一书中,Scott Meyers用了一章的篇幅来说明C++资源管理的一些内容,本文依次为基础。
1.RAII
RAII:Resourse Acquisition Is Initialization(资源获取即初始化),将资源放到管理对象中,管理对象使用析构函数来确保资源释放。
2.常见的智能指针
常见的智能指针有这些:
auto_ptr,share_ptr,weak_ptr,unique_ptr
下面我们将依次介绍这些智能指针的特点和实现:
- auto_ptr
auto_ptr通过new表达式来获取对象,被销毁时会自动删除它指向的对象。所以,不要让多个auto_ptr指向同一个对象。因此,auto_ptr具有唯一控制权。注意:在C++11 中弃用,在C++17中移除。具体见cppreference。我们举一个简单的例子:
//customer是一个类
std::auto_ptr<customer> pCus1(new customer());
std::auto_ptr<customer> pCus2(pCus1); //pCus2指向对象,pCus1设为NULL
pCus1 = pCus2;//pCus1指向对象,pCus2设为NULL
下面给出一个实现的版本,《More Effective C++》一书中的版本:
template<class T>
class auto_ptr {
//让所有的auto_ptr classes都成为一个auto_ptr class的friends
template<class U> friend class auto_ptr<U>;
public:
explicit auto_ptr(T* p = 0) : pointee(p) { }//default ctor
template<class U>
auto_ptr(auto_ptr<U>& rhs) : pointee(rhs.release()) { }//copy ctor
~auto_ptr() { delete pointee; } //dtor
template<class U>
auto_ptr<T>& operator=(auto_ptr<U>& rhs) {
//拷贝复制,注意证同测试
if(this != &rhs) reset(rhs.release());
return *this;
}
T& operator*() const { return *pointee; }
T* operator->() const { return pointee; }
T* get() const { return pointee; }
T* release() {
//资源转移
T* oldPointee = pointee;
pointee = 0;
return oldPointee;
}
void reset(T* p = 0) {
if(pointee != p) {
delete pointee;
pointee = p;
}
}
private:
T* pointee;
}
- share_ptr
share_ptr是一种引用计数型智能指针(reference-counting smart point, RCSP),多个share_ptr可以共享一个对象,具体见cppreference。
下面给出一个简单的实现版本,在github上找到的一个实现版本。
template<class T>
class share_ptr {
public:
private:
T* pointee;
unsigned int ptr_count; //引用计数
}
- weak_ptr
- unique_ptr