blob: 44b746fbcfd860c222c1d8ebe7b09b7d12148859 [file] [log] [blame]
Howard Hinnantc52f43e2010-08-22 00:59:46 +00001//===----------------------------------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Howard Hinnantb64f8b02010-11-16 22:09:02 +00005// This file is dual licensed under the MIT and the University of Illinois Open
6// Source Licenses. See LICENSE.TXT for details.
Howard Hinnantc52f43e2010-08-22 00:59:46 +00007//
8//===----------------------------------------------------------------------===//
9
10// <memory>
11
12// unique_ptr
13
14// Test swap
15
16#include <memory>
17#include <cassert>
18
19#include "../deleter.h"
20
21struct A
22{
23 int state_;
24 static int count;
25 A() : state_(0) {++count;}
26 explicit A(int i) : state_(i) {++count;}
27 A(const A& a) : state_(a.state_) {++count;}
28 A& operator=(const A& a) {state_ = a.state_; return *this;}
29 ~A() {--count;}
30
31 friend bool operator==(const A& x, const A& y)
32 {return x.state_ == y.state_;}
33};
34
35int A::count = 0;
36
37int main()
38{
39 {
40 A* p1 = new A(1);
41 std::unique_ptr<A, Deleter<A> > s1(p1, Deleter<A>(1));
42 A* p2 = new A(2);
43 std::unique_ptr<A, Deleter<A> > s2(p2, Deleter<A>(2));
44 assert(s1.get() == p1);
45 assert(*s1 == A(1));
46 assert(s1.get_deleter().state() == 1);
47 assert(s2.get() == p2);
48 assert(*s2 == A(2));
49 assert(s2.get_deleter().state() == 2);
50 swap(s1, s2);
51 assert(s1.get() == p2);
52 assert(*s1 == A(2));
53 assert(s1.get_deleter().state() == 2);
54 assert(s2.get() == p1);
55 assert(*s2 == A(1));
56 assert(s2.get_deleter().state() == 1);
57 assert(A::count == 2);
58 }
59 assert(A::count == 0);
60 {
61 A* p1 = new A[3];
62 std::unique_ptr<A[], Deleter<A[]> > s1(p1, Deleter<A[]>(1));
63 A* p2 = new A[3];
64 std::unique_ptr<A[], Deleter<A[]> > s2(p2, Deleter<A[]>(2));
65 assert(s1.get() == p1);
66 assert(s1.get_deleter().state() == 1);
67 assert(s2.get() == p2);
68 assert(s2.get_deleter().state() == 2);
69 swap(s1, s2);
70 assert(s1.get() == p2);
71 assert(s1.get_deleter().state() == 2);
72 assert(s2.get() == p1);
73 assert(s2.get_deleter().state() == 1);
74 assert(A::count == 6);
75 }
76 assert(A::count == 0);
77}