weak_from_this_test2.cpp 1.1 KB

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