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 // UNSUPPORTED: c++98, c++03 11 12 // <experimental/memory_resource> 13 14 // memory_resource * null_memory_resource() 15 16 #include <experimental/memory_resource> 17 #include <new> 18 #include <type_traits> 19 #include <cassert> 20 21 #include "test_macros.h" 22 #include "count_new.hpp" 23 24 namespace ex = std::experimental::pmr; 25 26 struct assert_on_compare : public ex::memory_resource 27 { 28 protected: 29 virtual void * do_allocate(size_t, size_t) 30 { assert(false); } 31 32 virtual void do_deallocate(void *, size_t, size_t) 33 { assert(false); } 34 35 virtual bool do_is_equal(ex::memory_resource const &) const noexcept 36 { assert(false); } 37 }; 38 39 void test_return() 40 { 41 { 42 static_assert(std::is_same< 43 decltype(ex::null_memory_resource()), ex::memory_resource* 44 >::value, ""); 45 } 46 // Test that the returned value is not null 47 { 48 assert(ex::null_memory_resource()); 49 } 50 // Test the same value is returned by repeated calls. 51 { 52 assert(ex::null_memory_resource() == ex::null_memory_resource()); 53 } 54 } 55 56 void test_equality() 57 { 58 // Same object 59 { 60 ex::memory_resource & r1 = *ex::null_memory_resource(); 61 ex::memory_resource & r2 = *ex::null_memory_resource(); 62 // check both calls returned the same object 63 assert(&r1 == &r2); 64 // check for proper equality semantics 65 assert(r1 == r2); 66 assert(r2 == r1); 67 assert(!(r1 != r2)); 68 assert(!(r2 != r1)); 69 // check the is_equal method 70 assert(r1.is_equal(r2)); 71 assert(r2.is_equal(r1)); 72 } 73 // Different types 74 { 75 ex::memory_resource & r1 = *ex::null_memory_resource(); 76 assert_on_compare c; 77 ex::memory_resource & r2 = c; 78 assert(r1 != r2); 79 assert(!(r1 == r2)); 80 assert(!r1.is_equal(r2)); 81 } 82 } 83 84 void test_allocate() 85 { 86 #ifndef TEST_HAS_NO_EXCEPTIONS 87 DisableAllocationGuard g; // null_memory_resource shouldn't allocate. 88 try { 89 ex::null_memory_resource()->allocate(1); 90 assert(false); 91 } catch (std::bad_alloc const &) { 92 // do nothing 93 } catch (...) { 94 assert(false); 95 } 96 #endif 97 } 98 99 void test_deallocate() 100 { 101 globalMemCounter.reset(); 102 103 int x = 42; 104 ex::null_memory_resource()->deallocate(nullptr, 0); 105 ex::null_memory_resource()->deallocate(&x, 0); 106 107 assert(globalMemCounter.checkDeleteCalledEq(0)); 108 assert(globalMemCounter.checkDeleteArrayCalledEq(0)); 109 } 110 111 int main() 112 { 113 test_return(); 114 test_equality(); 115 test_allocate(); 116 test_deallocate(); 117 } 118