C++资源管理之智能指针

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值