歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++智能指針 shared_ptr

C++智能指針 shared_ptr

日期:2017/3/1 9:08:34   编辑:Linux編程

shared_ptr 是一個標准的共享所有權的智能指針, 允許多個指針指向同一個對象. 定義在 memory 文件中(非memory.h), 命名空間為 std.

  shared_ptr 是為了解決 auto_ptr 在對象所有權上的局限性(auto_ptr 是獨占的), 在使用引用計數的機制上提供了可以共享所有權的智能指針, 當然這需要額外的開銷:
  (1) shared_ptr 對象除了包括一個所擁有對象的指針外, 還必須包括一個引用計數代理對象的指針.
  (2) 時間上的開銷主要在初始化和拷貝操作上, *和->操作符重載的開銷跟auto_ptr是一樣.
  (3) 開銷並不是我們不使用shared_ptr的理由, 永遠不要進行不成熟的優化, 直到性能分析器告訴你這一點.

  使用方法:

可以使用模板函數 make_shared 創建對象, make_shared 需指定類型('<>'中)及參數('()'內), 傳遞的參數必須與指定的類型的構造函數匹配. 如:
  std::shared_ptr<int> sp1 = std::make_shared<int>(10);
  std::shared_ptr<std::string> sp2 = std::make_shared<std::string>("Hello c++");
也可以定義 auto 類型的變量來保存 make_shared 的結果.
  auto sp3 = std::make_shared<int>(11);
  printf("sp3=%d\n", *sp3);
  auto sp4 = std::make_shared<std::string>("C++11");
  printf("sp4=%s\n", (*sp4).c_str());

成員函數

use_count 返回引用計數的個數
unique 返回是否是獨占所有權( use_count 為 1)
swap 交換兩個 shared_ptr 對象(即交換所擁有的對象)
reset 放棄內部對象的所有權或擁有對象的變更, 會引起原有對象的引用計數的減少
get 返回內部對象(指針), 由於已經重載了()方法, 因此和直接使用對象是一樣的.如 shared_ptr<int> sp(new int(1)); sp 與 sp.get()是等價的

以下代碼演示各個函數的用法與特點:

            std::shared_ptr<int> sp0(new int(2));
            std::shared_ptr<int> sp1(new int(11));
            std::shared_ptr<int> sp2 = sp1;
            printf("%d\n", *sp0);               // 2
            printf("%d\n", *sp1);               // 11
            printf("%d\n", *sp2);               // 11
            sp1.swap(sp0);
            printf("%d\n", *sp0);               // 11
            printf("%d\n", *sp1);               // 2
            printf("%d\n", *sp2);               // 11

            std::shared_ptr<int> sp3(new int(22));
            std::shared_ptr<int> sp4 = sp3;
            printf("%d\n", *sp3);               // 22
            printf("%d\n", *sp4);               // 22
            sp3.reset();                        
            printf("%d\n", sp3.use_count());    // 0
            printf("%d\n", sp4.use_count());    // 1
            printf("%d\n", sp3);                // 0
            printf("%d\n", sp4);                // 指向所擁有對象的地址
            
            std::shared_ptr<int> sp5(new int(22));
            std::shared_ptr<int> sp6 = sp5;
            std::shared_ptr<int> sp7 = sp5;
            printf("%d\n", *sp5);               // 22
            printf("%d\n", *sp6);               // 22
            printf("%d\n", *sp7);               // 22
            printf("%d\n", sp5.use_count());    // 3
            printf("%d\n", sp6.use_count());    // 3
            printf("%d\n", sp7.use_count());    // 3
            sp5.reset(new int(33));                        
            printf("%d\n", sp5.use_count());    // 1
            printf("%d\n", sp6.use_count());    // 2
            printf("%d\n", sp7.use_count());    // 2
            printf("%d\n", *sp5);               // 33
            printf("%d\n", *sp6);               // 22
            printf("%d\n", *sp7);               // 22

shared_ptr 的賦值構造函數和拷貝構造函數:
  auto r = std::make_shared<int>(); // r 的指向的對象只有一個引用, 其 use_count == 1
  auto q = r; (或auto q(r);) // 給 r 賦值, 令其指向另一個地址, q 原來指向的對象的引用計數減1(如果為0, 釋放內存), r指向的對象的引用計數加1, 此時 q 與 r 指向同一個對象, 並且其引用計數相同, 都為原來的值加1.
以下面的代碼測試:

            std::shared_ptr<int> sp1 = std::make_shared<int>(10);
            std::shared_ptr<int> sp2 = std::make_shared<int>(11);
            auto sp3 = sp2; 或 auto sp3(sp2);
            printf("sp1.use_count = %d\n", sp1.use_count());  // 1
            printf("sp2.use_count = %d\n", sp2.use_count());  // 2
            printf("sp3.use_count = %d\n", sp3.use_count());  // 2
            sp3 = sp1;
            printf("sp1.use_count = %d\n", sp1.use_count());  // 2
            printf("sp2.use_count = %d\n", sp2.use_count());  // 1
            printf("sp3.use_count = %d\n", sp3.use_count());  // 2 

何時需要使用 shared_ptr ?

(1) 程序不知道自己需要使用多少對象. 如使用窗口類, 使用 shared_ptr 為了讓多個對象能共享相同的底層數據.

            std::vector<std::string> v1; // 一個空的 vector
            // 在某個新的作用域中拷貝數據到 v1 中
            {
                std::vector<std::string> v2;
                v2.push_back("a");
                v2.push_back("b");
                v2.push_back("c");
                v1 = v2;
            } // 作用域結束時 v2 被銷毀, 數據被拷貝到 v1 中

(2) 程序不知道所需對象的准確類型.
(3) 程序需要在多個對象間共享數據.

自定義釋放器(函數)

  自定義釋放器(函數), 它能完成對 shared_ptr 中保存的指針進行釋放操作, 還能處理 shared_ptr 的內部對象未完成的部分工作.

  假設如下是一個連接管理類, 此類由於歷史原因, 無法在析構函數中進行斷開連接, 此時用自定義的釋放器可以很好的完成此工作:

        class CConnnect
        {
            void Disconnect() { PRINT_FUN(); }
        };

        void Deleter(CConnnect* obj)
        {
            obj->Disconnect(); // 做其它釋放或斷開連接等工作
            delete obj; // 刪除對象指針
        }
        
        std::shared_ptr<CConnnect> sps(new CConnnect, Deleter);

使用 shared_ptr 的注意事項

(1) shared_ptr 作為被保護的對象的成員時, 小心因循環引用造成無法釋放資源.
  假設 a 對象中含有一個 shared_ptr<CB> 指向 b 對象, b 對象中含有一個 shared_ptr<CA> 指向 a 對象, 並且 a, b 對象都是堆中分配的。
  考慮對象 b 中的 m_spa 是我們能最後一個看到 a 對象的共享智能指針, 其 use_count 為2, 因為對象 b 中持有 a 的指針, 所以當 m_spa 說再見時, m_spa 只是把 a 對象的 use_count 改成1; 對象 a 同理; 然後就失去了 a,b 對象的聯系.
  解決此方法是使用 weak_ptr 替換 shared_ptr . 以下為錯誤用法, 導致相互引用, 最後無法釋放對象

            class CB;
            class CA;

            class CA
            {
            public:
                CA(){}
                ~CA(){PRINT_FUN();}

                void Register(const std::shared_ptr<CB>& sp)
                {
                    m_sp = sp;
                }

            private:
                std::shared_ptr<CB> m_sp;
            };

            class CB
            {
            public:
                CB(){};
                ~CB(){PRINT_FUN();};

                void Register(const std::shared_ptr<CA>& sp)
                {
                    m_sp = sp;
                }

            private:
                std::shared_ptr<CA> m_sp;
            };

            std::shared_ptr<CA> spa(new CA);
            std::shared_ptr<CB> spb(new CB);

            spb->Register(spa);
            spa->Register(spb);
            printf("%d\n", spb.use_count()); // 2
            printf("%d\n", spa.use_count()); // 2

    運行上述代碼會發現 CA, CB 析構函數都不會打印. 因為他們都沒有釋放內存.

  (2) 小心對象內部生成 shared_ptr

            class Y : public std::enable_shared_from_this<Y>
            {
            public:
                std::shared_ptr<Y> GetSharePtr()
                {
                    return shared_from_this();
                }
            };

    對普通的類(沒有繼承 enable_shared_from_this) T 的 shared_ptr<T> p(new T). p 作為棧對象占8個字節,為了記錄( new T )對象的引用計數, p 會在堆上分配 16 個字節以保存引用計數等“智能信息”.
    share_ptr 沒有“嵌入(intrusive)”到T對象, 或者說T對象對 share_ptr 毫不知情.
    而 Y 對象則不同, Y 對象已經被“嵌入”了一些 share_ptr 相關的信息, 目的是為了找到“全局性”的那16字節的本對象的“智能信息”.

        考慮下面的代碼:
            Y y;
            std::shared_ptr<Y> spy = y.GetSharePtr(); // 錯誤, y 根本不是 new 創建的
            Y* y = new Y;
            std::shared_ptr<Y> spy = y->GetSharePtr(); // 錯誤, 問題依舊存在, 程序直接崩潰
        正確用法:
            std::shared_ptr<Y> spy(new Y);
            std::shared_ptr<Y> p = spy->GetSharePtr();
            printf("%d\n", p.use_count()); // 2

  (3) 小心多線程對引用計數的影響

首先, 如果是輕量級的鎖, 比如 InterLockIncrement 等, 對程序影響不大; 如果是重量級的鎖, 就要考慮因為 share_ptr 維護引用計數而造成的上下文切換開銷.
其次, 多線程同時對 shared_ptr 讀寫時, 行為不確定, 因為shared_ptr本身有兩個成員px,pi. 多線程同時對 px 讀寫要出問題, 與一個 int 的全局變量多線程讀寫會出問題的原因一樣.

(4) 與 weak_ptr 一起工作時, weak_ptr 在使用前需要檢查合法性

        std::weak_ptr<A> wp;
        {
            std::shared_ptr<A>  sp(new A);  //sp.use_count()==1
            wp = sp; //wp不會改變引用計數,所以sp.use_count()==1
            std::shared_ptr<A> sp2 = wp.lock(); //wp沒有重載->操作符。只能這樣取所指向的對象
        }
        printf("expired:%d\n", wp.expired()); // 1
        std::shared_ptr<A> sp_null = wp.lock(); //sp_null .use_count()==0;

上述代碼中 sp 和 sp2 離開了作用域, 其容納的對象已經被釋放了. 得到了一個容納 NULL 指針的 sp_null 對象.
在使用 wp 前需要調用 wp.expired() 函數判斷一下. 因為 wp 還仍舊存在, 雖然引用計數等於0,仍有某處“全局”性的存儲塊保存著這個計數信息.
直到最後一個 weak_ptr 對象被析構, 這塊“堆”存儲塊才能被回收, 否則 weak_ptr 無法知道自己所容納的那個指針資源的當前狀態.

  (5) shared_ptr 不支持數組, 如果使用數組, 需要自定義刪除器, 如下是一個利用 lambda 實現的刪除器:

      std::shared_ptr<int> sps(new int[10], [](int *p){delete[] p;});

    對於數組元素的訪問, 需使要使用 get 方法取得內部元素的地址後, 再加上偏移量取得.

            for (size_t i = 0; i < 10; i++)
            {
                *((int*)sps.get() + i) = 10 - i;
            }

            for (size_t i = 0; i < 10; i++)
            {
                printf("%d -- %d\n", i, *((int*)sps.get() + i));
            } 

VC中的源碼實現

template<class _Ty>
class _Ptr_base
{    // base class for shared_ptr and weak_ptr
public:
    typedef _Ptr_base<_Ty> _Myt;
    typedef _Ty _Elem;
    typedef _Elem element_type;

    _Ptr_base()
        : _Ptr(0), _Rep(0)
    {    // construct
    }

    _Ptr_base(_Myt&& _Right)
        : _Ptr(0), _Rep(0)
    {    // construct _Ptr_base object that takes resource from _Right
        _Assign_rv(_STD forward<_Myt>(_Right));
    }

    template<class _Ty2>
    _Ptr_base(_Ptr_base<_Ty2>&& _Right)
        : _Ptr(_Right._Ptr), _Rep(_Right._Rep)
    {    // construct _Ptr_base object that takes resource from _Right
        _Right._Ptr = 0;
        _Right._Rep = 0;
    }

    _Myt& operator=(_Myt&& _Right)
    {    // construct _Ptr_base object that takes resource from _Right
        _Assign_rv(_STD forward<_Myt>(_Right));
        return (*this);
    }

    void _Assign_rv(_Myt&& _Right)
    {    // assign by moving _Right
        if (this != &_Right)
            _Swap(_Right);
    }

    long use_count() const
    {    // return use count
        return (_Rep ? _Rep->_Use_count() : 0);
    }

    void _Swap(_Ptr_base& _Right)
    {    // swap pointers
        _STD swap(_Rep, _Right._Rep);
        _STD swap(_Ptr, _Right._Ptr);
    }

    template<class _Ty2>
    bool owner_before(const _Ptr_base<_Ty2>& _Right) const
    {    // compare addresses of manager objects
        return (_Rep < _Right._Rep);
    }

    void *_Get_deleter(const _XSTD2 type_info& _Type) const
    {    // return pointer to deleter object if its type is _Type
        return (_Rep ? _Rep->_Get_deleter(_Type) : 0);
    }

    _Ty *_Get() const
    {    // return pointer to resource
        return (_Ptr);
    }

    bool _Expired() const
    {    // test if expired
        return (!_Rep || _Rep->_Expired());
    }

    void _Decref()
    {    // decrement reference count
        if (_Rep != 0)
            _Rep->_Decref();
    }

    void _Reset()
    {    // release resource
        _Reset(0, 0);
    }

    template<class _Ty2>
    void _Reset(const _Ptr_base<_Ty2>& _Other)
    {    // release resource and take ownership of _Other._Ptr
        _Reset(_Other._Ptr, _Other._Rep, false);
    }

    template<class _Ty2>
    void _Reset(const _Ptr_base<_Ty2>& _Other, bool _Throw)
    {    // release resource and take ownership from weak_ptr _Other._Ptr
        _Reset(_Other._Ptr, _Other._Rep, _Throw);
    }

    template<class _Ty2>
    void _Reset(const _Ptr_base<_Ty2>& _Other, const _Static_tag&)
    {    // release resource and take ownership of _Other._Ptr
        _Reset(static_cast<_Elem *>(_Other._Ptr), _Other._Rep);
    }

    template<class _Ty2>
    void _Reset(const _Ptr_base<_Ty2>& _Other, const _Const_tag&)
    {    // release resource and take ownership of _Other._Ptr
        _Reset(const_cast<_Elem *>(_Other._Ptr), _Other._Rep);
    }

    template<class _Ty2>
    void _Reset(const _Ptr_base<_Ty2>& _Other, const _Dynamic_tag&)
    {    // release resource and take ownership of _Other._Ptr
        _Elem *_Ptr = dynamic_cast<_Elem *>(_Other._Ptr);
        if (_Ptr)
            _Reset(_Ptr, _Other._Rep);
        else
            _Reset();
    }

    template<class _Ty2>
    void _Reset(auto_ptr<_Ty2>& _Other)
    {    // release resource and take _Other.get()
        _Ty2 *_Px = _Other.get();
        _Reset0(_Px, new _Ref_count<_Elem>(_Px));
        _Other.release();
        _Enable_shared(_Px, _Rep);
    }

#if _HAS_CPP0X
    template<class _Ty2>
    void _Reset(_Ty *_Ptr, const _Ptr_base<_Ty2>& _Other)
    {    // release resource and alias _Ptr with _Other_rep
        _Reset(_Ptr, _Other._Rep);
    }
#endif /* _HAS_CPP0X */

    void _Reset(_Ty *_Other_ptr, _Ref_count_base *_Other_rep)
    {    // release resource and take _Other_ptr through _Other_rep
        if (_Other_rep)
            _Other_rep->_Incref();
        _Reset0(_Other_ptr, _Other_rep);
    }

    void _Reset(_Ty *_Other_ptr, _Ref_count_base *_Other_rep, bool _Throw)
    {    // take _Other_ptr through _Other_rep from weak_ptr if not expired
        // otherwise, leave in default state if !_Throw,
        // otherwise throw exception
        if (_Other_rep && _Other_rep->_Incref_nz())
            _Reset0(_Other_ptr, _Other_rep);
        else if (_Throw)
            _THROW_NCEE(bad_weak_ptr, 0);
    }

    void _Reset0(_Ty *_Other_ptr, _Ref_count_base *_Other_rep)
    {    // release resource and take new resource
        if (_Rep != 0)
            _Rep->_Decref();
        _Rep = _Other_rep;
        _Ptr = _Other_ptr;
    }

    void _Decwref()
    {    // decrement weak reference count
        if (_Rep != 0)
            _Rep->_Decwref();
    }

    void _Resetw()
    {    // release weak reference to resource
        _Resetw((_Elem *)0, 0);
    }

    template<class _Ty2>
    void _Resetw(const _Ptr_base<_Ty2>& _Other)
    {    // release weak reference to resource and take _Other._Ptr
        _Resetw(_Other._Ptr, _Other._Rep);
    }

    template<class _Ty2>
    void _Resetw(const _Ty2 *_Other_ptr, _Ref_count_base *_Other_rep)
    {    // point to _Other_ptr through _Other_rep
        _Resetw(const_cast<_Ty2*>(_Other_ptr), _Other_rep);
    }

    template<class _Ty2>
    void _Resetw(_Ty2 *_Other_ptr, _Ref_count_base *_Other_rep)
    {    // point to _Other_ptr through _Other_rep
        if (_Other_rep)
            _Other_rep->_Incwref();
        if (_Rep != 0)
            _Rep->_Decwref();
        _Rep = _Other_rep;
        _Ptr = _Other_ptr;
    }

private:
    _Ty *_Ptr;
    _Ref_count_base *_Rep;
    template<class _Ty0>
    friend class _Ptr_base;
};



template<class _Ty>
class shared_ptr
    : public _Ptr_base<_Ty>
{    // class for reference counted resource management
public:
    typedef shared_ptr<_Ty> _Myt;
    typedef _Ptr_base<_Ty> _Mybase;

    shared_ptr()
    {    // construct empty shared_ptr object
    }

    template<class _Ux>
    explicit shared_ptr(_Ux *_Px)
    {    // construct shared_ptr object that owns _Px
        _Resetp(_Px);
    }

    template<class _Ux,
    class _Dx>
        shared_ptr(_Ux *_Px, _Dx _Dt)
    {    // construct with _Px, deleter
        _Resetp(_Px, _Dt);
    }

    //#if _HAS_CPP0X

#if defined(_NATIVE_NULLPTR_SUPPORTED) \
    && !defined(_DO_NOT_USE_NULLPTR_IN_STL)

    shared_ptr(_STD nullptr_t)
    {    // construct with nullptr
        _Resetp((_Ty *)0);
    }

    template<class _Dx>
    shared_ptr(_STD nullptr_t, _Dx _Dt)
    {    // construct with nullptr, deleter
        _Resetp((_Ty *)0, _Dt);
    }

    template<class _Dx,
    class _Alloc>
        shared_ptr(_STD nullptr_t, _Dx _Dt, _Alloc _Ax)
    {    // construct with nullptr, deleter, allocator
        _Resetp((_Ty *)0, _Dt, _Ax);
    }
#endif /* defined(_NATIVE_NULLPTR_SUPPORTED) etc. */

    template<class _Ux,
    class _Dx,
    class _Alloc>
        shared_ptr(_Ux *_Px, _Dx _Dt, _Alloc _Ax)
    {    // construct with _Px, deleter, allocator
        _Resetp(_Px, _Dt, _Ax);
    }
    //#endif /* _HAS_CPP0X */

#if _HAS_CPP0X
    template<class _Ty2>
    shared_ptr(const shared_ptr<_Ty2>& _Right, _Ty *_Px)
    {    // construct shared_ptr object that aliases _Right
        this->_Reset(_Px, _Right);
    }
#endif /* _HAS_CPP0X */

    shared_ptr(const _Myt& _Other)
    {    // construct shared_ptr object that owns same resource as _Other
        this->_Reset(_Other);
    }

    template<class _Ty2>
    shared_ptr(const shared_ptr<_Ty2>& _Other,
        typename enable_if<is_convertible<_Ty2 *, _Ty *>::value,
        void *>::type * = 0)
    {    // construct shared_ptr object that owns same resource as _Other
        this->_Reset(_Other);
    }

    template<class _Ty2>
    explicit shared_ptr(const weak_ptr<_Ty2>& _Other,
        bool _Throw = true)
    {    // construct shared_ptr object that owns resource *_Other
        this->_Reset(_Other, _Throw);
    }

    template<class _Ty2>
    shared_ptr(auto_ptr<_Ty2>& _Other)
    {    // construct shared_ptr object that owns *_Other.get()
        this->_Reset(_Other);
    }

    template<class _Ty2>
    shared_ptr(const shared_ptr<_Ty2>& _Other, const _Static_tag& _Tag)
    {    // construct shared_ptr object for static_pointer_cast
        this->_Reset(_Other, _Tag);
    }

    template<class _Ty2>
    shared_ptr(const shared_ptr<_Ty2>& _Other, const _Const_tag& _Tag)
    {    // construct shared_ptr object for const_pointer_cast
        this->_Reset(_Other, _Tag);
    }

    template<class _Ty2>
    shared_ptr(const shared_ptr<_Ty2>& _Other, const _Dynamic_tag& _Tag)
    {    // construct shared_ptr object for dynamic_pointer_cast
        this->_Reset(_Other, _Tag);
    }

    shared_ptr(_Myt&& _Right)
        : _Mybase(_STD forward<_Myt>(_Right))
    {    // construct shared_ptr object that takes resource from _Right
    }

    template<class _Ty2>
    shared_ptr(shared_ptr<_Ty2>&& _Right,
        typename enable_if<is_convertible<_Ty2 *, _Ty *>::value,
        void *>::type * = 0)
        : _Mybase(_STD forward<shared_ptr<_Ty2> >(_Right))
    {    // construct shared_ptr object that takes resource from _Right
    }

#if _HAS_CPP0X
    template<class _Ux,
    class _Dx>
        shared_ptr(_STD unique_ptr<_Ux, _Dx>&& _Right)
    {    // construct from unique_ptr
        _Resetp(_Right.release(), _Right.get_deleter());
    }

    template<class _Ux,
    class _Dx>
        _Myt& operator=(unique_ptr<_Ux, _Dx>&& _Right)
    {    // move from unique_ptr
        shared_ptr(_STD move(_Right)).swap(*this);
        return (*this);
    }
#endif /* _HAS_CPP0X */

    _Myt& operator=(_Myt&& _Right)
    {    // construct shared_ptr object that takes resource from _Right
        shared_ptr(_STD move(_Right)).swap(*this);
        return (*this);
    }

    template<class _Ty2>
    _Myt& operator=(shared_ptr<_Ty2>&& _Right)
    {    // construct shared_ptr object that takes resource from _Right
        shared_ptr(_STD move(_Right)).swap(*this);
        return (*this);
    }

    void swap(_Myt&& _Right)
    {    // exchange contents with movable _Right
        _Mybase::swap(_STD move(_Right));
    }

    ~shared_ptr()
    {    // release resource
        this->_Decref();
    }

    _Myt& operator=(const _Myt& _Right)
    {    // assign shared ownership of resource owned by _Right
        shared_ptr(_Right).swap(*this);
        return (*this);
    }

    template<class _Ty2>
    _Myt& operator=(const shared_ptr<_Ty2>& _Right)
    {    // assign shared ownership of resource owned by _Right
        shared_ptr(_Right).swap(*this);
        return (*this);
    }

    template<class _Ty2>
    _Myt& operator=(auto_ptr<_Ty2>& _Right)
    {    // assign ownership of resource pointed to by _Right
        shared_ptr(_Right).swap(*this);
        return (*this);
    }

    void reset()
    {    // release resource and convert to empty shared_ptr object
        shared_ptr().swap(*this);
    }

    template<class _Ux>
    void reset(_Ux *_Px)
    {    // release, take ownership of _Px
        shared_ptr(_Px).swap(*this);
    }

    template<class _Ux,
    class _Dx>
        void reset(_Ux *_Px, _Dx _Dt)
    {    // release, take ownership of _Px, with deleter _Dt
        shared_ptr(_Px, _Dt).swap(*this);
    }

    //#if _HAS_CPP0X
    template<class _Ux,
    class _Dx,
    class _Alloc>
        void reset(_Ux *_Px, _Dx _Dt, _Alloc _Ax)
    {    // release, take ownership of _Px, with deleter _Dt, allocator _Ax
        shared_ptr(_Px, _Dt, _Ax).swap(*this);
    }
    //#endif /* _HAS_CPP0X */

    void swap(_Myt& _Other)
    {    // swap pointers
        this->_Swap(_Other);
    }

    _Ty *get() const
    {    // return pointer to resource
        return (this->_Get());
    }

    typename tr1::add_reference<_Ty>::type operator*() const
    {    // return reference to resource
        return (*this->_Get());
    }

    _Ty *operator->() const
    {    // return pointer to resource
        return (this->_Get());
    }

    bool unique() const
    {    // return true if no other shared_ptr object owns this resource
        return (this->use_count() == 1);
    }

    _OPERATOR_BOOL() const
    {    // test if shared_ptr object owns no resource
        return (this->_Get() != 0 ? _CONVERTIBLE_TO_TRUE : 0);
    }

private:
    template<class _Ux>
    void _Resetp(_Ux *_Px)
    {    // release, take ownership of _Px
        _TRY_BEGIN    // allocate control block and reset
            _Resetp0(_Px, new _Ref_count<_Ux>(_Px));
        _CATCH_ALL    // allocation failed, delete resource
            delete _Px;
        _RERAISE;
        _CATCH_END
    }

    template<class _Ux,
    class _Dx>
        void _Resetp(_Ux *_Px, _Dx _Dt)
    {    // release, take ownership of _Px, deleter _Dt
        _TRY_BEGIN    // allocate control block and reset
            _Resetp0(_Px, new _Ref_count_del<_Ux, _Dx>(_Px, _Dt));
        _CATCH_ALL    // allocation failed, delete resource
            _Dt(_Px);
        _RERAISE;
        _CATCH_END
    }

    //#if _HAS_CPP0X
    template<class _Ux,
    class _Dx,
    class _Alloc>
        void _Resetp(_Ux *_Px, _Dx _Dt, _Alloc _Ax)
    {    // release, take ownership of _Px, deleter _Dt, allocator _Ax
        typedef _Ref_count_del_alloc<_Ux, _Dx, _Alloc> _Refd;
        typename _Alloc::template rebind<_Refd>::other _Al = _Ax;

        _TRY_BEGIN    // allocate control block and reset
            _Refd *_Ptr = _Al.allocate(1);
        new (_Ptr) _Refd(_Px, _Dt, _Al);
        _Resetp0(_Px, _Ptr);
        _CATCH_ALL    // allocation failed, delete resource
            _Dt(_Px);
        _RERAISE;
        _CATCH_END
    }
    //#endif /* _HAS_CPP0X */

public:
    template<class _Ux>
    void _Resetp0(_Ux *_Px, _Ref_count_base *_Rx)
    {    // release resource and take ownership of _Px
        this->_Reset0(_Px, _Rx);
        _Enable_shared(_Px, _Rx);
    }
};

Copyright © Linux教程網 All Rights Reserved