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 // unique_ptr
12 
13 // test swap
14 
15 #include <memory>
16 #include <cassert>
17 
18 #include "test_macros.h"
19 #include "unique_ptr_test_helper.h"
20 
21 struct TT {
22   int state_;
23   static int count;
TTTT24   TT() : state_(-1) { ++count; }
TTTT25   explicit TT(int i) : state_(i) { ++count; }
TTTT26   TT(const TT& a) : state_(a.state_) { ++count; }
operator =TT27   TT& operator=(const TT& a) {
28     state_ = a.state_;
29     return *this;
30   }
~TTTT31   ~TT() { --count; }
32 
operator ==(const TT & x,const TT & y)33   friend bool operator==(const TT& x, const TT& y) {
34     return x.state_ == y.state_;
35   }
36 };
37 
38 int TT::count = 0;
39 
40 template <class T>
newValueInit(int size,int new_value)41 typename std::remove_all_extents<T>::type* newValueInit(int size,
42                                                         int new_value) {
43   typedef typename std::remove_all_extents<T>::type VT;
44   VT* p = newValue<T>(size);
45   for (int i = 0; i < size; ++i)
46     (p + i)->state_ = new_value;
47   return p;
48 }
49 
50 template <bool IsArray>
test_basic()51 void test_basic() {
52   typedef typename std::conditional<IsArray, TT[], TT>::type VT;
53   const int expect_alive = IsArray ? 5 : 1;
54 #if TEST_STD_VER >= 11
55   {
56     using U = std::unique_ptr<VT, Deleter<VT> >;
57     U u; ((void)u);
58     ASSERT_NOEXCEPT(u.swap(u));
59   }
60 #endif
61   {
62     TT* p1 = newValueInit<VT>(expect_alive, 1);
63     std::unique_ptr<VT, Deleter<VT> > s1(p1, Deleter<VT>(1));
64     TT* p2 = newValueInit<VT>(expect_alive, 2);
65     std::unique_ptr<VT, Deleter<VT> > s2(p2, Deleter<VT>(2));
66     assert(s1.get() == p1);
67     assert(*s1.get() == TT(1));
68     assert(s1.get_deleter().state() == 1);
69     assert(s2.get() == p2);
70     assert(*s2.get() == TT(2));
71     assert(s2.get_deleter().state() == 2);
72     s1.swap(s2);
73     assert(s1.get() == p2);
74     assert(*s1.get() == TT(2));
75     assert(s1.get_deleter().state() == 2);
76     assert(s2.get() == p1);
77     assert(*s2.get() == TT(1));
78     assert(s2.get_deleter().state() == 1);
79     assert(TT::count == (expect_alive * 2));
80   }
81   assert(TT::count == 0);
82 }
83 
main(int,char **)84 int main(int, char**) {
85   test_basic</*IsArray*/ false>();
86   test_basic<true>();
87 
88   return 0;
89 }
90