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 // shared_ptr 12 13 // template<class Y> shared_ptr(const shared_ptr<Y>& r, T *p); 14 15 #include <memory> 16 #include <cassert> 17 18 #include "test_macros.h" 19 20 struct B 21 { 22 static int count; 23 BB24 B() {++count;} BB25 B(const B&) {++count;} ~BB26 ~B() {--count;} 27 }; 28 29 int B::count = 0; 30 31 struct A 32 { 33 static int count; 34 AA35 A() {++count;} AA36 A(const A&) {++count;} ~AA37 ~A() {--count;} 38 }; 39 40 int A::count = 0; 41 main(int,char **)42int main(int, char**) 43 { 44 { 45 std::shared_ptr<A> pA(new A); 46 assert(pA.use_count() == 1); 47 48 { 49 B b; 50 std::shared_ptr<B> pB(pA, &b); 51 assert(A::count == 1); 52 assert(B::count == 1); 53 assert(pA.use_count() == 2); 54 assert(pB.use_count() == 2); 55 assert(pB.get() == &b); 56 } 57 assert(pA.use_count() == 1); 58 assert(A::count == 1); 59 assert(B::count == 0); 60 } 61 assert(A::count == 0); 62 assert(B::count == 0); 63 64 { 65 std::shared_ptr<A const> pA(new A); 66 assert(pA.use_count() == 1); 67 68 { 69 B const b; 70 std::shared_ptr<B const> pB(pA, &b); 71 assert(A::count == 1); 72 assert(B::count == 1); 73 assert(pA.use_count() == 2); 74 assert(pB.use_count() == 2); 75 assert(pB.get() == &b); 76 } 77 assert(pA.use_count() == 1); 78 assert(A::count == 1); 79 assert(B::count == 0); 80 } 81 assert(A::count == 0); 82 assert(B::count == 0); 83 84 int *pi = new int; 85 { 86 std::shared_ptr<int> p1(nullptr); 87 std::shared_ptr<int> p2(p1, pi); 88 assert(p2.get() == pi); 89 } 90 delete pi; 91 { 92 std::shared_ptr<int> p1(new int); 93 std::shared_ptr<int> p2(p1, nullptr); 94 assert(p2.get() == nullptr); 95 } 96 97 #if TEST_STD_VER > 17 && defined(_LIBCPP_VERSION) 98 // This won't pass when LWG-2996 is implemented. 99 { 100 std::shared_ptr<A> pA(new A); 101 assert(pA.use_count() == 1); 102 103 { 104 B b; 105 std::shared_ptr<B> pB(std::move(pA), &b); 106 assert(A::count == 1); 107 assert(B::count == 1); 108 assert(pA.use_count() == 2); 109 assert(pB.use_count() == 2); 110 assert(pB.get() == &b); 111 } 112 assert(pA.use_count() == 1); 113 assert(A::count == 1); 114 assert(B::count == 0); 115 } 116 assert(A::count == 0); 117 assert(B::count == 0); 118 #endif 119 120 return 0; 121 } 122