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