1
2// weak_from_test.cpp
3//
4// Copyright 2019 Peter Dimov
5//
6// Distributed under the Boost Software License, Version 1.0.
7// http://www.boost.org/LICENSE_1_0.txt)
8
9#include <boost/smart_ptr/enable_shared_from.hpp>
10#include <boost/shared_ptr.hpp>
11#include <boost/weak_ptr.hpp>
12#include <boost/core/lightweight_test.hpp>
13
14//
15
16class X
17{
18private:
19
20 int m_;
21
22public:
23
24 X(): m_() {}
25};
26
27class Y: public boost::enable_shared_from
28{
29};
30
31class Z: public X, public Y
32{
33public:
34
35 boost::weak_ptr<Z> weak_from_this()
36 {
37 return boost::weak_from( p: this );
38 }
39};
40
41void null_deleter( void const* )
42{
43}
44
45int main()
46{
47 boost::shared_ptr<Z> sp( new Z );
48 boost::weak_ptr<Z> p( sp );
49
50 {
51 boost::weak_ptr<Z> q = sp->weak_from_this();
52
53 BOOST_TEST_EQ( p.lock(), q.lock() );
54 BOOST_TEST( !( p < q ) && !( q < p ) );
55 }
56
57 Z v2( *sp );
58
59 {
60 boost::weak_ptr<Z> q = v2.weak_from_this();
61 BOOST_TEST( q.expired() );
62 }
63
64 *sp = Z();
65
66 {
67 boost::weak_ptr<Z> q = sp->weak_from_this();
68
69 BOOST_TEST_EQ( p.lock(), q.lock() );
70 BOOST_TEST( !( p < q ) && !( q < p ) );
71 }
72
73 {
74 boost::shared_ptr<Z> sp2( sp.get(), null_deleter );
75 }
76
77 {
78 boost::weak_ptr<Z> q = sp->weak_from_this();
79
80 BOOST_TEST_EQ( p.lock(), q.lock() );
81 BOOST_TEST( !( p < q ) && !( q < p ) );
82 }
83
84 {
85 boost::weak_ptr<Z> p2 = sp->weak_from_this();
86
87 BOOST_TEST( !p.expired() );
88 BOOST_TEST( !p2.expired() );
89
90 sp.reset();
91
92 BOOST_TEST( p.expired() );
93 BOOST_TEST( p2.expired() );
94 }
95
96 return boost::report_errors();
97}
98

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