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// void* operator new(std::size_t, std::nothrow_t const&);
10
11// Test that we can replace the operator by replacing `operator new(std::size_t)` (the throwing version).
12
13// This doesn't work when the shared library was built with exceptions disabled, because
14// we can't implement the non-throwing new from the throwing new in that case.
15// XFAIL: no-exceptions
16
17// UNSUPPORTED: sanitizer-new-delete
18// XFAIL: libcpp-no-vcruntime
19// XFAIL: LIBCXX-AIX-FIXME
20
21#include <new>
22#include <cstddef>
23#include <cstdlib>
24#include <cassert>
25
26#include "test_macros.h"
27
28int new_called = 0;
29int delete_called = 0;
30
31TEST_WORKAROUND_BUG_109234844_WEAK
32void* operator new(std::size_t s) TEST_THROW_SPEC(std::bad_alloc) {
33 ++new_called;
34 void* ret = std::malloc(s);
35 if (!ret) {
36 std::abort(); // placate MSVC's unchecked malloc warning (assert() won't silence it)
37 }
38 return ret;
39}
40
41void operator delete(void* p) TEST_NOEXCEPT {
42 ++delete_called;
43 std::free(p);
44}
45
46int main(int, char**) {
47 new_called = delete_called = 0;
48 int* x = DoNotOptimize(new (std::nothrow) int(3));
49 assert(x != nullptr);
50 ASSERT_WITH_OPERATOR_NEW_FALLBACKS(new_called == 1);
51
52 delete x;
53 ASSERT_WITH_OPERATOR_NEW_FALLBACKS(delete_called == 1);
54
55 return 0;
56}
57

source code of libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.single/new.size_nothrow.replace.indirect.pass.cpp