new_nothrow_replace.pass.cpp (1258B)
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 // test operator new nothrow by replacing only operator new 11 12 // UNSUPPORTED: sanitizer-new-delete 13 // XFAIL: libcpp-no-vcruntime 14 15 #include <new> 16 #include <cstddef> 17 #include <cstdlib> 18 #include <cassert> 19 #include <limits> 20 21 #include "test_macros.h" 22 23 int new_called = 0; 24 25 void* operator new(std::size_t s) TEST_THROW_SPEC(std::bad_alloc) 26 { 27 ++new_called; 28 void* ret = std::malloc(s); 29 if (!ret) std::abort(); // placate MSVC's unchecked malloc warning 30 return ret; 31 } 32 33 void operator delete(void* p) TEST_NOEXCEPT 34 { 35 --new_called; 36 std::free(p); 37 } 38 39 bool A_constructed = false; 40 41 struct A 42 { 43 A() {A_constructed = true;} 44 ~A() {A_constructed = false;} 45 }; 46 47 int main() 48 { 49 A *ap = new (std::nothrow) A; 50 DoNotOptimize(ap); 51 assert(ap); 52 assert(A_constructed); 53 assert(new_called); 54 delete ap; 55 DoNotOptimize(ap); 56 assert(!A_constructed); 57 assert(!new_called); 58 }