1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 // <memory>
10 
11 // weak_ptr
12 
13 // weak_ptr(const weak_ptr& r);
14 // weak_ptr(weak_ptr &&r)
15 
16 #include <memory>
17 #include <type_traits>
18 #include <cassert>
19 
20 #include "test_macros.h"
21 
22 struct B
23 {
24     static int count;
25 
BB26     B() {++count;}
BB27     B(const B&) {++count;}
~BB28     virtual ~B() {--count;}
29 };
30 
31 int B::count = 0;
32 
33 struct A
34     : public B
35 {
36     static int count;
37 
AA38     A() {++count;}
AA39     A(const A& other) : B(other) {++count;}
~AA40     ~A() {--count;}
41 };
42 
43 int A::count = 0;
44 
45 struct C
46 {
47     static int count;
48 
CC49     C() {++count;}
CC50     C(const C&) {++count;}
~CC51     virtual ~C() {--count;}
52 };
53 
54 int C::count = 0;
55 
56 template <class T>
source(std::shared_ptr<T> p)57 std::weak_ptr<T> source (std::shared_ptr<T> p) { return std::weak_ptr<T>(p); }
58 
59 #if TEST_STD_VER >= 11
60 template <class T>
sink(std::weak_ptr<T> &&)61 void sink (std::weak_ptr<T> &&) {}
62 #endif
63 
main(int,char **)64 int main(int, char**)
65 {
66     {
67         const std::shared_ptr<A> ps(new A);
68         const std::weak_ptr<A> pA(ps);
69         assert(pA.use_count() == 1);
70         assert(B::count == 1);
71         assert(A::count == 1);
72         {
73             std::weak_ptr<A> pB(pA);
74             assert(B::count == 1);
75             assert(A::count == 1);
76             assert(pB.use_count() == 1);
77             assert(pA.use_count() == 1);
78         }
79         assert(pA.use_count() == 1);
80         assert(B::count == 1);
81         assert(A::count == 1);
82     }
83     assert(B::count == 0);
84     assert(A::count == 0);
85     {
86         std::weak_ptr<A> pA;
87         assert(pA.use_count() == 0);
88         assert(B::count == 0);
89         assert(A::count == 0);
90         {
91             std::weak_ptr<A> pB(pA);
92             assert(B::count == 0);
93             assert(A::count == 0);
94             assert(pB.use_count() == 0);
95             assert(pA.use_count() == 0);
96         }
97         assert(pA.use_count() == 0);
98         assert(B::count == 0);
99         assert(A::count == 0);
100     }
101     assert(B::count == 0);
102     assert(A::count == 0);
103 
104 #if TEST_STD_VER >= 11
105     {
106         std::shared_ptr<A> ps(new A);
107         std::weak_ptr<A> pA = source(ps);
108         assert(pA.use_count() == 1);
109         assert(A::count == 1);
110         sink(std::move(pA)); // kill off the weak pointer
111     }
112     assert(B::count == 0);
113     assert(A::count == 0);
114 #endif
115 
116   return 0;
117 }
118