//---------------------------------------------------------------------------//
继续学习boost::shared_ptr,还是几乎是同一个程序,这回在linux下面编译。正好最近初学gdb,顺便用gdb去观察。
//---------------------------------------------------------------------------//
在" shared_ptr<TEST_SP> a(new TEST_SP);"这一句断下来之后,不断s步进:
16 shared_ptr<TEST_SP> a(new TEST_SP);
shared_ptr<TEST_SP> (this=0xbfe2a5d8, p=0x804a008)
at /usr/include/boost/shared_ptr.hpp:149
149 explicit shared_ptr( Y * p ): px( p ), pn( p ) // Y must be complete
shared_count<TEST_SP> (this=0xbfe2a5dc, p=0x804a008)
at /usr/include/boost/detail/shared_count.hpp:73
73 template<class Y> explicit shared_count( Y * p ): pi_( 0 )
82 pi_ = new sp_counted_impl_p<Y>( p );
sp_counted_impl_p (this=0x804a018, px=0x804a008)
at /usr/include/boost/detail/sp_counted_impl.hpp:67
67 explicit sp_counted_impl_p( X * px ): px_( px )
sp_counted_base (this=0x804a018)
at /usr/include/boost/detail/sp_counted_base_gcc_x86.hpp:109
109 sp_counted_base(): use_count_( 1 ), weak_count_( 1 )
可见和在vc中一样,构造a的时候构建了一个引用计数对象,a的两个成员一个指向所要管理的指针对象,另一个指向引用计数。
接下来执行到"shared_ptr<TEST_SP> b(a);"这一句,继续步进:
shared_ptr (this=0xbfe2a5d0) at /usr/include/boost/shared_ptr.hpp:131
131 {
shared_count (this=0xbfe2a5d4, r=@0xbfe2a5dc)
at /usr/include/boost/detail/shared_count.hpp:211
211 shared_count(shared_count const & r): pi_(r.pi_) // nothrow
216 if( pi_ != 0 ) pi_->add_ref_copy();
boost::detail::sp_counted_base::add_ref_copy (this=0x804a018)
at /usr/include/boost/detail/sp_counted_base_gcc_x86.hpp:133
133 atomic_increment( &use_count_ ) ;
0x08048807 133 atomic_increment( &use_count_ );
构造b时,引用计数加1。
类似地,当这两个智能指针退出作用域时,析构这两个智能指针的过程有所区别,最后那个指针需要负责销毁引用计数对象和管理的指针对象。
析构b:
~shared_ptr (this=0xbfe2a5d0) at /usr/include/boost/shared_ptr.hpp:131
131 {
~shared_count (this=0xbfe2a5d4)
at /usr/include/boost/detail/shared_count.hpp:205
205 if( pi_ != 0 ) pi_->release();
boost::detail::sp_counted_base::release (this=0x804a018)
at /usr/include/boost/detail/sp_counted_base_gcc_x86.hpp:143
143 if( atomic_exchange_and_add( &use_count_, -1 ) == 1 )
boost::detail::atomic_exchange_and_add (pw=0x804a01c, dv=-1)
at /usr/include/boost/detail/sp_counted_base_gcc_x86.hpp:50
析构a:
~shared_ptr (this=0xbfe2a5d8) at /usr/include/boost/shared_ptr.hpp:131
131 {
~shared_count (this=0xbfe2a5dc)
at /usr/include/boost/detail/shared_count.hpp:205
205 if( pi_ != 0 ) pi_->release();
boost::detail::sp_counted_base::release (this=0x804a018)
at /usr/include/boost/detail/sp_counted_base_gcc_x86.hpp:143
143 if( atomic_exchange_and_add( &use_count_, -1 ) == 1 )
boost::detail::atomic_exchange_and_add (pw=0x804a01c, dv=-1)
at /usr/include/boost/detail/sp_counted_base_gcc_x86.hpp:50
50 );
boost::detail::sp_counted_base::release (this=0x804a018)
at /usr/include/boost/detail/sp_counted_base_gcc_x86.hpp:145
145 dispose();
boost::detail::sp_counted_impl_p<TEST_SP_T>::dispose (this=0x804a018)
at /usr/include/boost/detail/sp_counted_impl.hpp:79
Boost学习--再窥shared_ptr
最新推荐文章于 2021-05-13 13:18:43 发布