boost shared_ptr計數分析

 

boost::shared_ptr<CTest>pFirst(new CTest(2));

 

boost::detail::shared_count pn;   // reference counter

 

   template<class Y>

   explicit shared_ptr( Y * p ): px( p ), pn( p )// Y must be complete

    {

       boost::detail::sp_enable_shared_from_this( this, p, p );

    }

 

   template<class Y> explicit shared_count( Y * p ): pi_( 0 )

    {

       pi_ = new sp_counted_impl_p<Y>( p );

       if( pi_ == 0 )

       {

           boost::checked_delete( p );

           boost::throw_exception( std::bad_alloc() );

       }

}

 

   explicit sp_counted_impl_p( X * px ): px_( px )

    {

}

 

boost::shared_ptr<CTest>pSecond(pFirst)

 

   shared_ptr( shared_ptr const & r ): px( r.px ), pn( r.pn ) // never throws

    {

}

 

shared_count(shared_countconst & r): pi_(r.pi_) // nothrow

{

    if( pi_ != 0 ) pi_->add_ref_copy();

}

 

void sp_counted_base::add_ref_copy()

{

    BOOST_INTERLOCKED_INCREMENT(&use_count_ );

}

 

boost::~shared_ptr

 

   ~shared_count() // nothrow

    {

       if( pi_ != 0 ) pi_->release();

}

 

    void sp_counted_base::release()// nothrow

    {

        if( BOOST_INTERLOCKED_DECREMENT(&use_count_ ) == 0 )

        {

           dispose();

            weak_release();

        }

    }

 

   virtual void sp_counted_impl_p::dispose() // nothrow

    {

        boost::checked_delete( px_ );

}

 

    void sp_counted_base::weak_release() //nothrow

    {

        if( BOOST_INTERLOCKED_DECREMENT(&weak_count_ ) == 0 )

        {

            destroy();

        }

    }

 

    virtual void sp_counted_base::destroy() // nothrow

    {

        delete this;

    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章