shared_ptr::lock no longer requires exceptions.

[SVN r44344]
This commit is contained in:
Peter Dimov
2008-04-12 14:27:22 +00:00
parent dbd62686a3
commit f85a1bf406
3 changed files with 29 additions and 25 deletions

View File

@@ -46,6 +46,8 @@ int const weak_count_id = 0x298C38A4;
#endif #endif
struct sp_nothrow_tag {};
class weak_count; class weak_count;
class shared_count class shared_count
@@ -216,6 +218,7 @@ public:
} }
explicit shared_count(weak_count const & r); // throws bad_weak_ptr when r.use_count() == 0 explicit shared_count(weak_count const & r); // throws bad_weak_ptr when r.use_count() == 0
shared_count( weak_count const & r, sp_nothrow_tag ); // constructs an empty *this when r.use_count() == 0
shared_count & operator= (shared_count const & r) // nothrow shared_count & operator= (shared_count const & r) // nothrow
{ {
@@ -248,6 +251,11 @@ public:
return use_count() == 1; return use_count() == 1;
} }
bool empty() const // nothrow
{
return pi_ == 0;
}
friend inline bool operator==(shared_count const & a, shared_count const & b) friend inline bool operator==(shared_count const & a, shared_count const & b)
{ {
return a.pi_ == b.pi_; return a.pi_ == b.pi_;
@@ -364,6 +372,17 @@ inline shared_count::shared_count( weak_count const & r ): pi_( r.pi_ )
} }
} }
inline shared_count::shared_count( weak_count const & r, sp_nothrow_tag ): pi_( r.pi_ )
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
, id_(shared_count_id)
#endif
{
if( pi_ != 0 && !pi_->add_ref_lock() )
{
pi_ = 0;
}
}
} // namespace detail } // namespace detail
} // namespace boost } // namespace boost

View File

@@ -220,6 +220,15 @@ public:
px = r.px; px = r.px;
} }
template<class Y>
shared_ptr( weak_ptr<Y> const & r, boost::detail::sp_nothrow_tag ): px( 0 ), pn( r.pn, boost::detail::sp_nothrow_tag() ) // never throws
{
if( !pn.empty() )
{
px = r.px;
}
}
template<class Y> template<class Y>
shared_ptr(shared_ptr<Y> const & r): px(r.px), pn(r.pn) // never throws shared_ptr(shared_ptr<Y> const & r): px(r.px), pn(r.pn) // never throws
{ {

View File

@@ -93,31 +93,7 @@ public:
shared_ptr<T> lock() const // never throws shared_ptr<T> lock() const // never throws
{ {
#if defined(BOOST_HAS_THREADS) return shared_ptr<element_type>( *this, boost::detail::sp_nothrow_tag() );
// optimization: avoid throw overhead
if(expired())
{
return shared_ptr<element_type>();
}
try
{
return shared_ptr<element_type>(*this);
}
catch(bad_weak_ptr const &)
{
// Q: how can we get here?
// A: another thread may have invalidated r after the use_count test above.
return shared_ptr<element_type>();
}
#else
// optimization: avoid try/catch overhead when single threaded
return expired()? shared_ptr<element_type>(): shared_ptr<element_type>(*this);
#endif
} }
long use_count() const // never throws long use_count() const // never throws