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 objects
46 // and a delete expression deletes them. The brace-init requires C++11.
47 {
48#if TEST_STD_VER >= 11
49 LifetimeInformation infos[3];
50 TrackLifetime* x = new (std::nothrow) TrackLifetime[3]{infos[0], infos[1], infos[2]};
51 assert(x != nullptr);
52
53 void* addresses[3] = {&x[0], &x[1], &x[2]};
54 assert(infos[0].address_constructed == addresses[0]);
55 assert(infos[1].address_constructed == addresses[1]);
56 assert(infos[2].address_constructed == addresses[2]);
57
58 delete[] x;
59 assert(infos[0].address_destroyed == addresses[0]);
60 assert(infos[1].address_destroyed == addresses[1]);
61 assert(infos[2].address_destroyed == addresses[2]);
62#endif
63 }
64
65 return 0;
66}
67

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