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

source code of boost/libs/smart_ptr/test/weak_from_test2.cpp