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

source code of libcxx/test/std/utilities/memory/util.smartptr/util.smartptr.shared/util.smartptr.shared.spec/swap.pass.cpp