2 // shared_from_raw_test - based on shared_from_this_test
4 // Copyright (c) 2002, 2003, 2014 Peter Dimov
6 // Distributed under the Boost Software License, Version 1.0.
8 // See accompanying file LICENSE_1_0.txt or copy at
9 // http://www.boost.org/LICENSE_1_0.txt
12 #if defined(__GNUC__) && __GNUC__ > 4
13 # pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor"
16 #include <boost/smart_ptr/enable_shared_from_raw.hpp>
17 #include <boost/shared_ptr.hpp>
19 #include <boost/detail/lightweight_test.hpp>
38 virtual boost::shared_ptr<X> getX() = 0;
45 boost::shared_ptr<Y> createY();
49 boost::shared_ptr<Y> py = createY();
50 BOOST_TEST(py.get() != 0);
51 BOOST_TEST(py.use_count() == 1);
55 boost::shared_ptr<X> px = py->getX();
56 BOOST_TEST(px.get() != 0);
57 BOOST_TEST(py.use_count() == 2);
61 #if !defined( BOOST_NO_RTTI )
62 boost::shared_ptr<Y> py2 = boost::dynamic_pointer_cast<Y>(px);
63 BOOST_TEST(py.get() == py2.get());
64 BOOST_TEST(!(py < py2 || py2 < py));
65 BOOST_TEST(py.use_count() == 3);
68 catch( boost::bad_weak_ptr const& )
70 BOOST_ERROR( "py->getX() failed" );
82 return boost::report_errors();
85 // virtual inheritance to stress the implementation
86 // (prevents Y* -> impl*, enable_shared_from_raw* -> impl* casts)
88 class impl: public X, public virtual Y, public virtual boost::enable_shared_from_raw
96 virtual boost::shared_ptr<X> getX()
98 boost::shared_ptr<impl> pi = boost::shared_from_raw( this );
99 BOOST_TEST( pi.get() == this );
104 // intermediate impl2 to stress the implementation
106 class impl2: public impl
110 boost::shared_ptr<Y> createY()
112 boost::shared_ptr<Y> pi(new impl2);
118 boost::shared_ptr<Y> pi(static_cast<impl2*>(0));
123 struct V: public boost::enable_shared_from_raw
129 boost::shared_ptr<V> p( new V );
133 boost::shared_ptr<V> q = boost::shared_from_raw( p.get() );
134 BOOST_TEST( p == q );
135 BOOST_TEST( !(p < q) && !(q < p) );
137 catch( boost::bad_weak_ptr const & )
139 BOOST_ERROR( "shared_from_this( p.get() ) failed" );
146 // shared_from_raw differs from shared_from_this;
147 // it will not throw here and will create a shared_ptr
149 boost::shared_ptr<V> r = boost::shared_from_raw( &v2 );
151 // check if the shared_ptr is correct and that it does
152 // not share ownership with p
154 BOOST_TEST( r.get() == &v2 );
155 BOOST_TEST( p != r );
156 BOOST_TEST( (p < r) || (r < p) );
158 catch( boost::bad_weak_ptr const & )
160 BOOST_ERROR("shared_from_raw( &v2 ) failed");
166 boost::shared_ptr<V> r = boost::shared_from_raw( p.get() );
167 BOOST_TEST( p == r );
168 BOOST_TEST( !(p < r) && !(r < p) );
170 catch( boost::bad_weak_ptr const & )
172 BOOST_ERROR("shared_from_raw( p.get() ) threw bad_weak_ptr after *p = V()");