C++之shared_ptr總結,shared_ptr總結

來源:互聯網
上載者:User

C++之shared_ptr總結,shared_ptr總結

Share_ptr也是一種智能指標。類比於auto_ptr學習。所以推薦先學習auto_ptr,再來學習shared_ptr。本部落格的前兩個就是auto_ptr的總結。希望感興趣的朋友可以看看。

 

Shared_ptr和auto_ptr最大的區別就是,shared_ptr解決了指標間共用對象所有權的問題,也就是auto_ptr中的賦值的奇怪問題。所以滿足了容器的要求,可以用於容器中。而auto_ptr顯然禁止共用對象所有權,不可以用於容器中。

       int * a=new int(2);       shared_ptr<int> sp1(a);       shared_ptr<int> sp2(sp1);     OK

當然shared_ptr作為一種智能指標,也擁有和shared_ptr一些相似的性質。它們本質上都是類,但是使用起來像指標。它們都是為瞭解決防止記憶體流失的解決方案。都是運用了RAII技術來實現的。

 

注意:使用shared_ptr也要引用標頭檔#include<memory>

 

由於shared_ptr的源碼過於複雜,我們不給出源碼。類比於auto_ptr學習.

 

1. 首先類shared_ptr有兩個成員變數。T * px和unsign long * pn;

T * px;顯然和auto_ptr一樣,用於儲存對象的指標。

pn用於記錄有多少個shared_ptr擁有同一個對象。pn是shared_ptr對象間共用的,類似於static成員變數。 

template<class T>class shared_ptr{private:       T *px; // contained pointer    unsignedlong* pn; // reference counter}

總結:其實shared_ptr的原理,就是使用px來記錄指標,使用*pn來記錄px指向的對象的擁有者share_ptr的個數,當一個shared_ptr對象達到範圍時,不會釋放資源,只有當*pn變為0的時候,才會釋放指標指向的資源。

 

2. 一個簡單實現的源碼(仍然看懂源碼還是最重要的。)

#pragma once//shared_ptr的簡單實現版本//基於引用記數的智能指標//它可以和stl容器完美的配合namespace boost{template<class T>class shared_ptr{typedef unsigned longsize_type;private:       T *px; // contained pointer   size_type* pn; // reference counterpublic://建構函式---------------------------------------------------2/*int* a=new int(2);shared_ptr<int> sp;shared_ptr<int> sp(a);*/explicitshared_ptr(T* p=0) : px(p){   pn = new size_type(1);} /*Derived d;shared_ptr<Base> ap(d);*/template<typename Y>shared_ptr(Y* py){pn = newsize_type(1);px=py;}//copy建構函式------------------------------------------------/*int * a=new int;shared_ptr<int> sp(a);shared_ptr<int> sp1(sp);*/shared_ptr(constshared_ptr& r) throw(): px(r.px){++*r.pn;pn = r.pn;} /*shared_ptr<Derived>sp1(derived);shared_ptr<Base> sp2(sp1);*/template<typename Y>shared_ptr(constshared_ptr<Y>& r)//用於多態{px = r.px;++*r.pn;pn = r.pn; //shared_count::op= doesn't throw}//重載賦值operator=--------------------------------------------shared_ptr& operator=(const shared_ptr& r) throw(){if(this== &r) return *this;dispose();px = r.px;++*r.pn;pn = r.pn;return *this;}template<typename Y>shared_ptr& operator=(const shared_ptr<Y>& r)//用於多態{dispose();px = r.px;++*r.pn;pn = r.pn; //shared_count::op= doesn't throwreturn *this;} ~shared_ptr() { dispose(); }void reset(T* p=0){if ( px == p ) return;if (--*pn == 0){ delete(px); }else{ // allocate newreference// counter// fix: prevent leak if new throwstry { pn = new size_type; }catch (...) {// undo effect of —*pn above to// meet effects guarantee++*pn;delete(p);throw;} // catch} // allocate newreference counter*pn = 1;px = p;} // resetreference operator*()const throw(){ return *px; }pointer operator->()const throw(){ return px; }pointer get() constthrow(){ returnpx; }size_type use_count() constthrow()//{ return *pn; }bool unique() const throw()//{ return *pn ==1; }private:void dispose() throw(){if (--*pn == 0){ delete px; delete pn; }}}; // shared_ptrtemplate<typename A,typenameB>inline bool operator==(shared_ptr<A>const & l, shared_ptr<B> const & r){return l.get() == r.get();}template<typename A,typenameB>inline bool operator!=(shared_ptr<A>const & l, shared_ptr<B> const & r){return l.get() != r.get();}}//namespace boost


要注意的地方:

 

3. Shared_ptr和auto_ptr都有類似的規定:

看看它們的copy構造和重載賦值都可以看出:

不允許

       int* a=new int(2);       shared_ptr<int>sp=a;//  error       sp=a;//    error

就是不允許使用一個純指標給一個智能指標賦值或copy構造。只能使用智能指標給另一個智能指標賦值或copy構造。

       int* a=new int(2);   shared_ptr<int> sp(a);//建構函式    shared_ptr<int> sp1(sp);//copy構造       sp1=sp;//賦值

在auto_ptr中也是相同的。

 

4. 注意shared_ptr的幾個函數

Ø     Reset()函數:重設函數

標準中的是:

      int* a=new int(2);       int* b=new int(3);    shared_ptr<int> sp2(a);    shared_ptr<int> sp1(a);   shared_ptr<int> sp(a);       sp.reset(b);      sp.reset();      sp.reset(sp2);  -----!!!也是可以的。

使得sp獲得b的擁有權。失去a的擁有權。注意這會使得a的擁有者少1.當a的擁有者變為0時,就會釋放a的資源。

Ø     Swap()函數:交換函數

       int* a=new int(2);       shared_ptr<int> sp(a);       shared_ptr<int> sp1(a);       sp.swap(sp1);

就是兩個shared_ptr中的px和pn都互換一下。

Ø     Get()函數:返回px

Ø     Use_count函數:返回*pn,就是對象的擁有者的數量。

Ø     Unique函數:令*pn=1;讓對象的擁有者的數量變為1。返回bool

Ø     同時share_ptr也重載了*和->

 

5. tr1中重載了幾個有關shared_ptr的符號:

template<classT, class U>

booloperator==(shared_ptr<T> const& a, shared_ptr<U> const& b);

判斷擁有的對象是否是一樣的

 

template<classT, class U>

 bool operator!=(shared_ptr<T> const&a, shared_ptr<U> const& b);

判斷擁有的對象是否是不一樣的

 

template<classT, class U>

 bool operator<(shared_ptr<T>const& a, shared_ptr<U> const& b);

重載了小於符號,在STL中的LIST中非常有用。

       int* a=new int(2);       int* b=new int(3);       shared_ptr<int> sp(a);       shared_ptr<int> sp1(b);       if(sp<sp1)              cout<<"2222"<<endl;

6. 注意真實中shared_ptr中沒有public dispose這個函數,這裡只是為了避免代碼重複。

 

7. 注意shared_ptr中的解構函式中不是直接釋放資源,而是調用了dispose函數,如果*pn==0了,才會釋放資源。

 

8.shared_ptr的多線程的安全性

shared_ptr 本身不是 100%安全執行緒的。它的引用計數本身是安全且無鎖的,但對象的讀寫則不是,因為shared_ptr有兩個資料成員,讀寫操作不能原子化。根據文檔,shared_ptr的安全執行緒層級和內建類型、標準庫容器、string一樣,即:

  • 一個 shared_ptr 實體可被多個線程同時讀取;
  • 兩個的 shared_ptr 實體可以被兩個線程同時寫入,“析構”算寫操作;
  • 如果要從多個線程讀寫同一個 shared_ptr 對象,那麼需要加鎖。

 

發現了兩個非常有意思的東西:

1. 看tr1中的源碼中發現兩個這樣的東西:

template<class Y, classD> shared_ptr(Y * p, D d);

template<class Y, classD> void reset(Y * p, D d);

其中的D d是個什麼東西?源碼的解釋是d是一個deleter(刪除器)。至此我們突然發現我們可以給shared_ptr指定一個刪除器,當*pn==0的時候,不去釋放資源,而去調用我們自己給它的刪除器。

 

當shared_ptr的引用次數為0的時候,share_ptr就會調用釋放函數來釋放資源。

當我們希望引用次數為0的時候,shared_ptr不釋放資源,而是調用我們指定的操作的時候,就會用到D d;

void foo(int * d){       cout<<"1234"<<endl;} int _tmain(int argc, _TCHAR* argv[]){       int* a=new int(2);       shared_ptr<int> sp(a,foo);       shared_ptr<int> sp1(sp);       sp.reset();       sp1.reset();       //_CrtDumpMemoryLeaks();       system("pause");       return 0;}


注意!:

1. 指定的刪除器的參數必須是int*;和shared_ptr<int>中的int對應。不能是其他的,或者為空白也是錯的。因為系統會把shared_ptr的對象px賦給刪除器的參數,我們也可以在刪除器中釋放資源。

2. 只有a的引用次數為0才會調用,所以如果沒有sp1.reset()。也不會調用foo函數。

 

2. 使用shared_ptr的時候,要小心,想一想操作的內在含義才去做。

1>

       int* a=new int(2);       shared_ptr<int> sp(a);       shared_ptr<int> sp1(sp);       sp.reset();//--------(1)       sp.reset();//--------(2)


這裡(1)是重設了sp,注意(2)是沒有任何作用的,不能使得a的引用次數變為0.想一想reset的函數內部,(2)的時候,sp中的對象pn已經為空白了,則不能改變*pn的值了。

 

2>

     int* a=new int(2);       shared_ptr<int> sp(a);//----------(1)       shared_ptr<int> sp1(a);//---------(2)

注意:這裡的(2)也是不對的。想一想shared_ptr的建構函式,(1)的時候,sp的px指向a,且*pn為1.而(2)的時候,px指向a,且*pn也是1.這顯然就問題了。a被引用了2次,但是*pn為1.在最後範圍達到的時候,就會釋放2次記憶體,這就會引發異常。

 

總結:shared_ptr和auto_ptr的區別。

Shared_ptr有兩個變數,一個記錄對象地址,一個記錄引用次數

Auto_ptr只有一個變數,用來記錄對象地址

 

Shared_ptr可用多個shared_ptr擁有一個資源。

Auto_ptr只能一個auto_ptr擁有一個資源

 

Shared_ptr可以實現賦值的正常操作,使得兩個地址指向同一資源

Auto_ptr的賦值很奇怪,源失去資源擁有權,目標擷取資源擁有權

 

Shared_ptr到達範圍時,不一定會釋放資源。

Auto_ptr到達作用於時,一定會釋放資源。

 

Shared_ptr存在多線程的安全性問題,而auto_ptr沒有。

 

Shared_ptr可用於容器中,而auto_ptr一般不可以用於容器中。


Shared_ptr可以在建構函式、reset函數的時候允許指定刪除器。而auto_ptr不能。

 

還有這裡說一句:使用智能指標(不管shared_ptr還是auto_ptr),都要清除源碼內部的實現原理,使用起來才不會錯。而且使用的時候,一定要想一想函數內部的實現原理再去使用。切記小心。



vs2008對於C++的shared_ptr

shared_ptr需要VS2008 SP1以上才內建有,標頭檔為#include <memory>,或者使用boost庫(boost::shared_ptr),標頭檔為#include <boost/shared_ptr.hpp>

vs2008 error C2039: “shared_ptr”: 不是“std::tr1”的成員

vs2008建立的c++項目中用到了std::tr1::shared_ptr,
編譯時間報錯:error C2039: “shared_ptr”: 不是“std::tr1”的成員。
原因:未安裝vs2008 SP1
VS90sp1-KB945140-CHS.exe:
www.microsoft.com/...58056E
VS2008SP1CHSX1512981.iso:
www.microsoft.com/...B5CE61
若 不安裝vs2008 SP1,也可使用Boost的實現boost::shared_ptr
 
怎:建立與使用shared_ptr執行個體

make_shared 是異常安全的。它使用同一調用分配的記憶體控制塊和該資源從而減少構造開銷。如果不使用 make_shared,則必須使用顯式新的運算式建立對象,然後將其傳遞給 shared_ptr 建構函式之前。下面的樣本示範各種方式與新的對象同時聲明和初始化 shared_ptr。VBC#C++F#JScriptPowerShell No code example is currently available or this language may not be supported. 下面的樣本示範如何聲明和初始化採用對象共用所有權另一 shared_ptr已指派的 shared_ptr 執行個體。假定,sp2 是初始化的 shared_ptr。VBC#C++F#JScriptPowerShell No code example is currently available or this language may not be supported. shared_ptr 也很有用在標準模板庫 (STL) 容器,當您使用"複製元素的演算法時。可以封裝在 shared_ptr的元素,然後將其複製到完全理解的其他容器基礎記憶體有效,只要不需要且不再。下面的樣本在向量示範如何使用在 shared_ptr 執行個體的 replace_copy_if 演算法。VBC#C++F#JScriptPowerShell No code example is currently available or this language may not be supported. 可以使用 dynamic_pointer_cast、static_pointer_cast和const_pointer_cast 轉換shared_ptr。這些功能類似於 dynamic_cast、static_cast和const_cast 運算子。下面的樣本示範如何測試每個元素的衍生類別型在基類 shared_ptr 向量的,然後複製元素並顯示有關它們的資訊。VBC#C++F#JScriptPowerShell No code example is currently available or this language may not be supported. 可以通過以下方式通過 shared_ptr 到另一個函數:通過shared_ptr 值。此調用複製建構函式,會遞增引用計數,並使被呼叫者所有者。具有此操作的少量系統開銷,可能是有意義的根據經曆 shared_ptr 對象通過。使用此選項,當代碼協定 (提示或顯式) 時在調用方和被呼叫者之間要求被呼叫者是所有者。通過shared_ptr 引用或常數引用。在這種情況下,引用計數不增加,因此,被呼叫者可以訪問指標,只要調用方不超出範圍。或者,則被呼叫者可以決定建立基於引用的 shared_ptr 從而形成一個共用的所有者。使用此選項,當調用方不瞭解被呼叫者時,或者,如果必須通過 shared_ptr 和若要出於效能原因時避免複製操作。通過基礎指標或引用為基礎對象。這使得被呼叫者使用對象,但是,不使共用所有權或擴充生存期。如果被呼叫者建立原始指標的 shared_ptr,新 shared_ptr 與原來的是獨立的和不控制此類基礎資源。使用此選項,則在調用方和被呼叫者之間的協定的清單指定時調用方保留 shared_ptr 生存期的所有權。當您決定如何通過 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.