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 // template<class Y> weak_ptr& operator=(const weak_ptr<Y>& r); 14 // template<class Y> weak_ptr& operator=(weak_ptr<Y>&& r); 15 16 #include <memory> 17 #include <type_traits> 18 #include <utility> 19 #include <cassert> 20 21 #include "test_macros.h" 22 23 struct B 24 { 25 static int count; 26 BB27 B() {++count;} BB28 B(const B&) {++count;} ~BB29 virtual ~B() {--count;} 30 }; 31 32 int B::count = 0; 33 34 struct A 35 : public B 36 { 37 static int count; 38 AA39 A() {++count;} AA40 A(const A& other) : B(other) {++count;} ~AA41 ~A() {--count;} 42 }; 43 44 int A::count = 0; 45 main(int,char **)46int main(int, char**) 47 { 48 { 49 const std::shared_ptr<A> ps(new A); 50 const std::weak_ptr<A> pA(ps); 51 { 52 std::weak_ptr<B> pB; 53 pB = pA; 54 assert(B::count == 1); 55 assert(A::count == 1); 56 assert(pB.use_count() == 1); 57 assert(pA.use_count() == 1); 58 } 59 assert(pA.use_count() == 1); 60 assert(B::count == 1); 61 assert(A::count == 1); 62 } 63 assert(B::count == 0); 64 assert(A::count == 0); 65 66 { 67 const std::shared_ptr<A> ps(new A); 68 std::weak_ptr<A> pA(ps); 69 { 70 std::weak_ptr<B> pB; 71 pB = std::move(pA); 72 assert(B::count == 1); 73 assert(A::count == 1); 74 assert(pB.use_count() == 1); 75 } 76 assert(B::count == 1); 77 assert(A::count == 1); 78 } 79 assert(B::count == 0); 80 assert(A::count == 0); 81 82 #if TEST_STD_VER > 14 83 { 84 const std::shared_ptr<A[]> ps(new A[8]); 85 const std::weak_ptr<A[]> p1(ps); 86 { 87 std::weak_ptr<const A[]> p2; 88 p2 = p1; 89 assert(A::count == 8); 90 assert(p2.use_count() == 1); 91 assert(p1.use_count() == 1); 92 } 93 assert(p1.use_count() == 1); 94 assert(A::count == 8); 95 } 96 assert(A::count == 0); 97 98 { 99 const std::shared_ptr<A[]> ps(new A[8]); 100 std::weak_ptr<A[]> p1(ps); 101 { 102 std::weak_ptr<const A[]> p2; 103 p2 = std::move(p1); 104 assert(A::count == 8); 105 assert(p2.use_count() == 1); 106 } 107 assert(A::count == 8); 108 } 109 assert(A::count == 0); 110 #endif 111 112 return 0; 113 } 114