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>代替。
這兩個方案具有更高的靈活性和更好的安全性,所付出的代價幾乎可以忽略不計。