1 #include <boost/config.hpp>
3 #if defined(BOOST_MSVC)
4 #pragma warning(disable: 4786) // identifier truncated in debug info
5 #pragma warning(disable: 4710) // function not inlined
6 #pragma warning(disable: 4711) // function selected for automatic inline expansion
7 #pragma warning(disable: 4514) // unreferenced inline removed
11 // shared_from_this_test.cpp
13 // Copyright (c) 2002, 2003 Peter Dimov
15 // Distributed under the Boost Software License, Version 1.0. (See
16 // accompanying file LICENSE_1_0.txt or copy at
17 // http://www.boost.org/LICENSE_1_0.txt)
21 #include <boost/enable_shared_from_this.hpp>
22 #include <boost/shared_ptr.hpp>
24 #include <boost/detail/lightweight_test.hpp>
43 virtual boost::shared_ptr<X> getX() = 0;
50 boost::shared_ptr<Y> createY();
54 boost::shared_ptr<Y> py = createY();
55 BOOST_TEST(py.get() != 0);
56 BOOST_TEST(py.use_count() == 1);
60 boost::shared_ptr<X> px = py->getX();
61 BOOST_TEST(px.get() != 0);
62 BOOST_TEST(py.use_count() == 2);
66 #if !defined( BOOST_NO_RTTI )
67 boost::shared_ptr<Y> py2 = boost::dynamic_pointer_cast<Y>(px);
68 BOOST_TEST(py.get() == py2.get());
69 BOOST_TEST(!(py < py2 || py2 < py));
70 BOOST_TEST(py.use_count() == 3);
73 catch( boost::bad_weak_ptr const& )
75 BOOST_ERROR( "py->getX() failed" );
87 return boost::report_errors();
90 // virtual inheritance to stress the implementation
91 // (prevents Y* -> impl*, enable_shared_from_this<impl>* -> impl* casts)
93 class impl: public X, public virtual Y, public virtual boost::enable_shared_from_this<impl>
101 virtual boost::shared_ptr<X> getX()
103 boost::shared_ptr<impl> pi = shared_from_this();
104 BOOST_TEST(pi.get() == this);
109 // intermediate impl2 to stress the implementation
111 class impl2: public impl
115 boost::shared_ptr<Y> createY()
117 boost::shared_ptr<Y> pi(new impl2);
123 boost::shared_ptr<Y> pi(static_cast<impl2*>(0));
128 struct V: public boost::enable_shared_from_this<V>
134 boost::shared_ptr<V> p(new V);
138 boost::shared_ptr<V> q = p->shared_from_this();
140 BOOST_TEST(!(p < q) && !(q < p));
142 catch( boost::bad_weak_ptr const & )
144 BOOST_ERROR( "p->shared_from_this() failed" );
151 boost::shared_ptr<V> r = v2.shared_from_this();
152 BOOST_ERROR("v2.shared_from_this() failed to throw");
154 catch( boost::bad_weak_ptr const & )
161 boost::shared_ptr<V> r = p->shared_from_this();
163 BOOST_TEST(!(p < r) && !(r < p));
165 catch( boost::bad_weak_ptr const & )
167 BOOST_ERROR("p->shared_from_this() threw bad_weak_ptr after *p = V()");