swap.pass.cpp revision b64f8b07c104c6cc986570ac8ee0ed16a9f23976
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// 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}
78