weak_ptr.pass.cpp (1639B)
1 //===----------------------------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is dual licensed under the MIT and the University of Illinois Open 6 // Source Licenses. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 // <memory> 11 12 // shared_ptr 13 14 // template<class Y> explicit shared_ptr(const weak_ptr<Y>& r); 15 16 #include <memory> 17 #include <cassert> 18 19 #include "test_macros.h" 20 21 struct B 22 { 23 static int count; 24 25 B() {++count;} 26 B(const B&) {++count;} 27 virtual ~B() {--count;} 28 }; 29 30 int B::count = 0; 31 32 struct A 33 : public B 34 { 35 static int count; 36 37 A() {++count;} 38 A(const A&) {++count;} 39 ~A() {--count;} 40 }; 41 42 int A::count = 0; 43 44 int main() 45 { 46 #ifndef TEST_HAS_NO_EXCEPTIONS 47 { 48 std::weak_ptr<A> wp; 49 try 50 { 51 std::shared_ptr<A> sp(wp); 52 assert(false); 53 } 54 catch (std::bad_weak_ptr&) 55 { 56 } 57 assert(A::count == 0); 58 } 59 #endif 60 { 61 std::shared_ptr<A> sp0(new A); 62 std::weak_ptr<A> wp(sp0); 63 std::shared_ptr<A> sp(wp); 64 assert(sp.use_count() == 2); 65 assert(sp.get() == sp0.get()); 66 assert(A::count == 1); 67 } 68 assert(A::count == 0); 69 #ifndef TEST_HAS_NO_EXCEPTIONS 70 { 71 std::shared_ptr<A> sp0(new A); 72 std::weak_ptr<A> wp(sp0); 73 sp0.reset(); 74 try 75 { 76 std::shared_ptr<A> sp(wp); 77 assert(false); 78 } 79 catch (std::bad_weak_ptr&) 80 { 81 } 82 } 83 assert(A::count == 0); 84 #endif 85 }