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// asan and msan will not call the new handler.
12// UNSUPPORTED: sanitizer-new-delete
13
14#include <new>
15#include <cstddef>
16#include <cassert>
17#include <limits>
18
19#include "test_macros.h"
20#include "../types.h"
21
22int new_handler_called = 0;
23
24void my_new_handler() {
25 ++new_handler_called;
26 std::set_new_handler(nullptr);
27}
28
29int main(int, char**) {
30 // Test that we can call the function directly
31 {
32 void* x = operator new(10, std::nothrow);
33 assert(x != nullptr);
34 operator delete(x, std::nothrow);
35 }
36
37 // Test that the new handler is called and we return nullptr if allocation fails
38 {
39 std::set_new_handler(my_new_handler);
40 void* x = operator new(std::numeric_limits<std::size_t>::max(), std::nothrow);
41 assert(new_handler_called == 1);
42 assert(x == nullptr);
43 }
44
45 // Test that a new expression constructs the right object
46 // and a delete expression deletes it
47 {
48 LifetimeInformation info;
49 TrackLifetime* x = new (std::nothrow) TrackLifetime(info);
50 assert(x != nullptr);
51 assert(info.address_constructed == x);
52
53 const auto old_x = x;
54 delete x;
55 assert(info.address_destroyed == old_x);
56 }
57
58 return 0;
59}
60

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