4 // A regression test for enable_shared_from_this
6 // Copyright (c) 2008 Peter Dimov
8 // Distributed under the Boost Software License, Version 1.0.
10 // See accompanying file LICENSE_1_0.txt or copy at
11 // http://www.boost.org/LICENSE_1_0.txt)
14 #include <boost/enable_shared_from_this.hpp>
15 #include <boost/shared_ptr.hpp>
16 #include <boost/weak_ptr.hpp>
17 #include <boost/detail/lightweight_test.hpp>
21 class X: public boost::enable_shared_from_this< X >
32 X& operator=( X const& );
40 explicit X( int expected ): destroyed_( 0 ), deleted_( 0 ), expected_( expected )
47 BOOST_TEST( deleted_ == expected_ );
48 BOOST_TEST( destroyed_ == 0 );
53 typedef void (*deleter_type)( X* );
55 static void deleter( X * px )
60 static void deleter2( X * px )
71 BOOST_TEST( X::instances == 0 );
75 BOOST_TEST( X::instances == 1 );
78 BOOST_TEST( X::instances == 0 );
81 std::auto_ptr<X> px( new X( 0 ) );
82 BOOST_TEST( X::instances == 1 );
85 BOOST_TEST( X::instances == 0 );
88 boost::shared_ptr<X> px( new X( 0 ) );
89 BOOST_TEST( X::instances == 1 );
91 boost::weak_ptr<X> wp( px );
92 BOOST_TEST( !wp.expired() );
96 BOOST_TEST( wp.expired() );
99 BOOST_TEST( X::instances == 0 );
103 boost::shared_ptr<X> px( &x, X::deleter );
104 BOOST_TEST( X::instances == 1 );
106 X::deleter_type * pd = boost::get_deleter<X::deleter_type>( px );
107 BOOST_TEST( pd != 0 && *pd == X::deleter );
109 boost::weak_ptr<X> wp( px );
110 BOOST_TEST( !wp.expired() );
114 BOOST_TEST( wp.expired() );
117 BOOST_TEST( X::instances == 0 );
120 boost::shared_ptr<X> px( new X( 1 ), X::deleter2 );
121 BOOST_TEST( X::instances == 1 );
123 X::deleter_type * pd = boost::get_deleter<X::deleter_type>( px );
124 BOOST_TEST( pd != 0 && *pd == X::deleter2 );
126 boost::weak_ptr<X> wp( px );
127 BOOST_TEST( !wp.expired() );
131 BOOST_TEST( wp.expired() );
134 BOOST_TEST( X::instances == 0 );
137 struct V: public boost::enable_shared_from_this<V>
155 boost::shared_ptr<W> p( new W );
161 boost::shared_ptr<void> pv( p );
162 BOOST_TEST( pv.get() == p );
163 BOOST_TEST( pv.use_count() == 1 );
168 void operator()( void const* ) const {}
173 boost::shared_ptr<V> pv( new V );
174 boost::shared_ptr<V> pv2( pv.get(), null_deleter() );
175 BOOST_TEST( pv2.get() == pv.get() );
176 BOOST_TEST( pv2.use_count() == 1 );
183 boost::shared_ptr<V> p1( &v, null_deleter() );
184 BOOST_TEST( p1.get() == &v );
185 BOOST_TEST( p1.use_count() == 1 );
189 p1->shared_from_this();
193 BOOST_ERROR( "p1->shared_from_this() failed" );
198 boost::shared_ptr<V> p2( &v, null_deleter() );
199 BOOST_TEST( p2.get() == &v );
200 BOOST_TEST( p2.use_count() == 1 );
204 p2->shared_from_this();
208 BOOST_ERROR( "p2->shared_from_this() failed" );
220 return boost::report_errors();