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 // void swap(shared_ptr& r); 15 16 #include <memory> 17 #include <cassert> 18 19 struct A 20 { 21 static int count; 22 AA23 A() {++count;} AA24 A(const A&) {++count;} ~AA25 ~A() {--count;} 26 }; 27 28 int A::count = 0; 29 main()30int main() 31 { 32 { 33 A* ptr1 = new A; 34 A* ptr2 = new A; 35 std::shared_ptr<A> p1(ptr1); 36 { 37 std::shared_ptr<A> p2(ptr2); 38 p1.swap(p2); 39 assert(p1.use_count() == 1); 40 assert(p1.get() == ptr2); 41 assert(p2.use_count() == 1); 42 assert(p2.get() == ptr1); 43 assert(A::count == 2); 44 } 45 assert(p1.use_count() == 1); 46 assert(p1.get() == ptr2); 47 assert(A::count == 1); 48 } 49 assert(A::count == 0); 50 { 51 A* ptr1 = new A; 52 A* ptr2 = 0; 53 std::shared_ptr<A> p1(ptr1); 54 { 55 std::shared_ptr<A> p2; 56 p1.swap(p2); 57 assert(p1.use_count() == 0); 58 assert(p1.get() == ptr2); 59 assert(p2.use_count() == 1); 60 assert(p2.get() == ptr1); 61 assert(A::count == 1); 62 } 63 assert(p1.use_count() == 0); 64 assert(p1.get() == ptr2); 65 assert(A::count == 0); 66 } 67 assert(A::count == 0); 68 { 69 A* ptr1 = 0; 70 A* ptr2 = new A; 71 std::shared_ptr<A> p1; 72 { 73 std::shared_ptr<A> p2(ptr2); 74 p1.swap(p2); 75 assert(p1.use_count() == 1); 76 assert(p1.get() == ptr2); 77 assert(p2.use_count() == 0); 78 assert(p2.get() == ptr1); 79 assert(A::count == 1); 80 } 81 assert(p1.use_count() == 1); 82 assert(p1.get() == ptr2); 83 assert(A::count == 1); 84 } 85 assert(A::count == 0); 86 { 87 A* ptr1 = 0; 88 A* ptr2 = 0; 89 std::shared_ptr<A> p1; 90 { 91 std::shared_ptr<A> p2; 92 p1.swap(p2); 93 assert(p1.use_count() == 0); 94 assert(p1.get() == ptr2); 95 assert(p2.use_count() == 0); 96 assert(p2.get() == ptr1); 97 assert(A::count == 0); 98 } 99 assert(p1.use_count() == 0); 100 assert(p1.get() == ptr2); 101 assert(A::count == 0); 102 } 103 assert(A::count == 0); 104 } 105