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

来源:互联网 发布:为什么c语言是黑窗口 编辑:程序博客网 时间:2024/05/16 05:04

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>代替。

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

原创粉丝点击