@@ -61,11 +61,84 @@ void case3()
6161{
6262 using namespace std ;
6363
64+ shared_ptr<int > ptr1 (new int (10 ));
65+ assert (*ptr1 = 10 );
66+
67+ shared_ptr<string> ptr2 (new string (" hello" ));
68+ assert (*ptr2 == " hello" );
69+
70+ auto ptr3 = make_shared<int >(42 );
71+ assert (ptr3 && *ptr3 == 42 );
72+
73+ auto ptr4 = make_shared<string>(" zelda" );
74+ assert (!ptr4->empty ());
75+ }
76+
77+ void case4 ()
78+ {
79+ using namespace std ;
80+
6481 auto ptr1 = make_shared<int >(42 );
65- assert (ptr1 && *ptr1 == 42 );
82+ assert (ptr1 && ptr1.unique () );
83+
84+ auto ptr2 = ptr1;
85+ assert (ptr1 && ptr2);
86+
87+ assert (ptr1 == ptr2);
88+ assert (!ptr1.unique () && ptr1.use_count () == 2 );
89+ assert (!ptr2.unique () && ptr2.use_count () == 2 );
90+ }
91+
92+ class DemoShared final
93+ {
94+ public:
95+ DemoShared () = default ;
96+ ~DemoShared ()
97+ {
98+ // do some blocking thing ...
99+ }
100+ };
101+
102+ class Node final
103+ {
104+ public:
105+ using this_type = Node;
106+ // using shared_type = std::shared_ptr<this_type>;
107+ using shared_type = std::weak_ptr<this_type>;
108+ public:
109+ shared_type next;
110+ public:
111+ Node () = default ;
112+ ~Node ()
113+ {
114+ using namespace std ;
115+ cout << " node dtor" << endl;
116+ }
117+ };
118+
119+ void case5 ()
120+ {
121+ using namespace std ;
122+
123+ auto n1 = make_shared<Node>();
124+ auto n2 = make_shared<Node>();
125+
126+ assert (n1.use_count () == 1 );
127+ assert (n2.use_count () == 1 );
128+
129+ n1->next = n2;
130+ n2->next = n1;
131+
132+ assert (n1.use_count () == 1 );
133+ assert (n2.use_count () == 1 );
134+
135+ if (!n1->next .expired ()) {
136+ auto ptr = n1->next .lock ();
137+ assert (ptr == n2);
138+ }
66139
67- auto ptr2 = make_shared<string>( " god of war " );
68- assert (!ptr2-> empty () );
140+ // assert(n1.use_count() == 2 );
141+ // assert(n2.use_count() == 2 );
69142}
70143
71144int main ()
@@ -75,6 +148,8 @@ int main()
75148 case1 ();
76149 case2 ();
77150 case3 ();
151+ case4 ();
152+ case5 ();
78153
79154 cout << " smart_ptr demo" << endl;
80155}
0 commit comments