forked from boostorg/smart_ptr
'shared_from_this' added.
[SVN r14561]
This commit is contained in:
@ -313,6 +313,28 @@ template<typename T> inline T * get_pointer(shared_ptr<T> const & p)
|
||||
return p.get();
|
||||
}
|
||||
|
||||
// shared_from_this() creates a shared_ptr from a raw pointer (usually 'this')
|
||||
|
||||
namespace detail
|
||||
{
|
||||
|
||||
inline void sp_assert_counted_base(boost::counted_base const *)
|
||||
{
|
||||
}
|
||||
|
||||
template<class T> inline T * sp_remove_const(T const * p)
|
||||
{
|
||||
return const_cast<T *>(p);
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
template<class T> shared_ptr<T> shared_from_this(T * p)
|
||||
{
|
||||
detail::sp_assert_counted_base(p);
|
||||
return shared_ptr<T>(detail::sp_remove_const(p));
|
||||
}
|
||||
|
||||
} // namespace boost
|
||||
|
||||
#ifdef BOOST_MSVC
|
||||
|
@ -112,6 +112,16 @@ public:
|
||||
std::cout << "Z(" << this << ")::~Z()\n";
|
||||
}
|
||||
|
||||
boost::shared_ptr<Z> shared_this()
|
||||
{
|
||||
return boost::shared_from_this(this);
|
||||
}
|
||||
|
||||
boost::shared_ptr<Z const> shared_this() const
|
||||
{
|
||||
return boost::shared_from_this(this);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
Z(Z const &);
|
||||
@ -331,9 +341,24 @@ int test_main(int, char * [])
|
||||
|
||||
{
|
||||
// test intrusive counting
|
||||
boost::shared_ptr<void> pv(new Z);
|
||||
|
||||
boost::shared_ptr<void> pv(new Z);
|
||||
boost::shared_ptr<Z> pz = boost::shared_static_cast<Z>(pv);
|
||||
BOOST_TEST(pz.use_count() == pz->use_count());
|
||||
|
||||
// test shared_from_this
|
||||
|
||||
boost::shared_ptr<Z> pz2 = pz->shared_this();
|
||||
|
||||
Z const & z = *pz2;
|
||||
|
||||
boost::shared_ptr<Z const> pz3 = z.shared_this();
|
||||
|
||||
BOOST_TEST(pz.use_count() == pz->use_count());
|
||||
BOOST_TEST(pz2.use_count() == pz2->use_count());
|
||||
BOOST_TEST(pz3.use_count() == pz3->use_count());
|
||||
BOOST_TEST(pz.use_count() == pz2.use_count());
|
||||
BOOST_TEST(pz.use_count() == pz3.use_count());
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user