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::align_val_t);
10
11// Test that we can replace the operator by defining our own.
12
13// UNSUPPORTED: c++03, c++11, c++14
14// UNSUPPORTED: sanitizer-new-delete
15
16// Libc++ when built for z/OS doesn't contain the aligned allocation functions,
17// nor does the dynamic library shipped with z/OS.
18// XFAIL: target={{.+}}-zos{{.*}}
19
20#include <new>
21#include <cstddef>
22#include <cstdlib>
23#include <cstdint>
24#include <cassert>
25#include <limits>
26
27#include "test_macros.h"
28#include "../types.h"
29
30int new_called = 0;
31int delete_called = 0;
32
33alignas(OverAligned) char DummyData[alignof(OverAligned) * 3];
34
35void* operator new[](std::size_t s, std::align_val_t a) {
36 assert(s <= sizeof(DummyData));
37 assert(static_cast<std::size_t>(a) == alignof(OverAligned));
38 ++new_called;
39 return DummyData;
40}
41
42void operator delete[](void*, std::align_val_t) noexcept {
43 ++delete_called;
44 // nothing to delete, we didn't actually allocate in `operator new`
45}
46
47int main(int, char**) {
48 // Test with an overaligned type
49 {
50 new_called = delete_called = 0;
51 OverAligned* x = new OverAligned[3];
52 assert(static_cast<void*>(x) == DummyData);
53 assert(new_called == 1);
54
55 delete[] x;
56 assert(delete_called == 1);
57 }
58
59 // Test with a type that is right on the verge of being overaligned
60 {
61 new_called = delete_called = 0;
62 MaxAligned* x = new MaxAligned[3];
63 assert(x != nullptr);
64 assert(new_called == 0);
65
66 delete[] x;
67 assert(delete_called == 0);
68 }
69
70 // Test with a type that is clearly not overaligned
71 {
72 new_called = delete_called = 0;
73 int* x = new int[3];
74 assert(x != nullptr);
75 assert(new_called == 0);
76
77 delete[] x;
78 assert(delete_called == 0);
79 }
80
81 return 0;
82}
83

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