[内存管理]智能指针之shared_array

shared_array类似shared_ptr,它包装了new[]操作符在堆上分配的动态数组,同样使用引用计数机制为动态数组提供了一个代理,可以在程序的生命同期里长期存在,直到没有任何引用后才释放内存。

类摘要:

template<class T> class shared_array{

public:
     explicit shared_array(T *p = 0);
	 template<class D> shared_array(T *p,D d);
	 ~shared_array();
	 
	 shared_array(shared_array const & r);
	 shared_array &operator=(shared_array const &r);
	 
	 void reset(T *p = 0);
	 template<class D> void reset(T *p, D d);
	 
	 T & operator[](std::ptrdiff_t i) const() const;
	 T *get() const;
	 
	 bool unique() const;
	 long use_count() const;
	 
	 void swap(shared_array<T> & b);
};

shared_array与shared_ptr的区别如下:

1:构造函数接受的指针p必须是new[]的结果,而不能是new表达式。

2:提供operator[]操作符重载,可以像普通数组一样用下标访问元素。

3:没有*、->操作符重载,因为shared_array持有的不是一个普通指针。

4:析构函数使用delete[]释放资源,而不是delete。

 

使用示例:

#include <iostream>
#include <boost/smart_ptr.hpp>
using namespace boost;
using namespace std;
int main(){
     //shared_array<int> sp(new int[100]);	
     //a dynamic array
     int *p = new int[100];
     //shared_array agent dynamic array
     shared_array<int> sa(p);
     //shared array,add reference count
     shared_array<int> sa2 = sa;
     sa[0] = 10;
     assert(sa2[0] == 10);
     cout << "use count:" << sa.use_count() << endl;
     cout << "No Problem..." << endl;
     //out of scope,remove dynamic array automatically
}


运行结果:

use count:2
No Problem...

shared_array是shared_ptr和scoped_array的结合体,既具有shared_ptr的优点,也有scoped_array的缺点。

在使用shared_array重载的operator[]要注意,shared_array不提供数组索引的范围检查,如果超过了动态数组大小的索引或者是负数索引将引发未定义行为。

shared_array能力有限,大多情况下可以用shared_ptr<std::vector>或者std::vector<shared_ptr>代替。

这两个方案具有更高的灵活性和更好的安全性,所付出的代价几乎可以忽略不计。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值