3.5 shared_array
shared_array类似shared_ptr,它包装了new[]操作符在堆上分配的动态数组,同样使用引用计数机制为动态数组提供了一个代理,可以在程序的生命周期里长期存在,直到没有任何引用后才释放内存。
3.5.1 类摘要
shared_array的类摘要如下:
- 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是相同的,主要区别如下:
构造函数接受的指针p必须是new[]的结果,而不能是new表达式的结果;
提供operator[]操作符重载,可以像普通数组一样用下标访问元素;
没有*、->操作符重载,因为shared_array持有的不是一个普通指针;
析构函数使用delete[]释放资源,而不是delete。