weak_from_test2.cpp 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // weak_from_test2.cpp
  2. //
  3. // Tests weak_from in a destructor
  4. //
  5. // Copyright 2014, 2015, 2019 Peter Dimov
  6. //
  7. // Distributed under the Boost Software License, Version 1.0.
  8. // http://www.boost.org/LICENSE_1_0.txt
  9. #include <boost/smart_ptr/enable_shared_from.hpp>
  10. #include <boost/weak_ptr.hpp>
  11. #include <boost/core/lightweight_test.hpp>
  12. class X: public boost::enable_shared_from
  13. {
  14. private:
  15. boost::weak_ptr<X> px_;
  16. public:
  17. X()
  18. {
  19. boost::weak_ptr<X> p1 = weak_from( this );
  20. BOOST_TEST( p1._empty() );
  21. BOOST_TEST( p1.expired() );
  22. }
  23. void check()
  24. {
  25. boost::weak_ptr<X> p2 = weak_from( this );
  26. BOOST_TEST( !p2.expired() );
  27. BOOST_TEST( p2.lock().get() == this );
  28. px_ = p2;
  29. }
  30. ~X()
  31. {
  32. boost::weak_ptr<X> p3 = weak_from( this );
  33. BOOST_TEST( p3.expired() );
  34. BOOST_TEST( !(px_ < p3) && !(p3 < px_) );
  35. }
  36. };
  37. int main()
  38. {
  39. {
  40. boost::shared_ptr< X > px( new X );
  41. px->check();
  42. }
  43. return boost::report_errors();
  44. }