[記憶體管理]智能指標之shared_array

來源:互聯網
上載者:User

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

這兩個方案具有更高的靈活性和更好的安全性,所付出的代價幾乎可以忽略不計。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.