3.5.1 类摘要

2013-10-07 13:13:19 · 作者: · 浏览: 70

3.5  shared_array

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

3.5.1  类摘要

shared_array的类摘要如下:

  1. template<class T> class shared_array {  
  2.  
  3. public:  
  4.       explicit shared_array(T * p = 0);  
  5.       template<class D> shared_array(T * p, D d);  
  6.       ~shared_array();  
  7.  
  8.       shared_array(shared_array const & r);  
  9.  
  10.       shared_array & operator=(shared_array const & r);  
  11.  
  12.       void reset(T * p = 0);  
  13.       template<class D> void reset(T * p, D d);  
  14.  
  15.       T & operator[](std::ptrdiff_t i) const() const;  
  16.       T * get() const;  
  17.  
  18.       bool unique() const;  
  19.       long use_count() const;  
  20.  
  21.       void swap(shared_array<T> & b);  
  22. }; 

shared_array的接口与功能几乎是与shared_ptr是相同的,主要区别如下:

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

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

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

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