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