Debian Codegraph @

gcc/testsuite/g++.dg/cpp26/constexpr-new2.C

raw
1 // C++26 P2747R2 - constexpr placement new
2 // { dg-do compile { target c++26 } }
3 // { dg-skip-if "requires hosted libstdc++ for memory allocator" { ! hostedlib } }
4
5 #include <memory>
6 #include <new>
7
8 #ifndef __cpp_lib_constexpr_new
9 # error "__cpp_lib_constexpr_new"
10 #elif __cpp_lib_constexpr_new < 202406L
11 # error "__cpp_lib_constexpr_new < 202406"
12 #endif
13
14 struct S {
15 constexpr S () : a (42), b (43) {}
16 constexpr S (int c, int d) : a (c), b (d) {}
17 int a, b;
18 };
19 struct T {
20 int a, b;
21 };
22
23 constexpr bool
24 foo ()
25 {
26 std::allocator<int> a;
27 auto b = a.allocate (3);
28 ::new (b) int ();
29 ::new (b + 1) int (1);
30 ::new (b + 2) int {2};
31 if (b[0] != 0 || b[1] != 1 || b[2] != 2)
32 return false;
33 a.deallocate (b, 3);
34 std::allocator<S> c;
35 auto d = c.allocate (4);
36 ::new (d) S;
37 ::new (d + 1) S ();
38 ::new (d + 2) S (7, 8);
39 ::new (d + 3) S { 9, 10 };
40 if (d[0].a != 42 || d[0].b != 43
41 || d[1].a != 42 || d[1].b != 43
42 || d[2].a != 7 || d[2].b != 8
43 || d[3].a != 9 || d[3].b != 10)
44 return false;
45 d[0].~S ();
46 d[1].~S ();
47 d[2].~S ();
48 d[3].~S ();
49 c.deallocate (d, 4);
50 std::allocator<T> e;
51 auto f = e.allocate (3);
52 ::new (f) T ();
53 ::new (f + 1) T (7, 8);
54 ::new (f + 2) T { .a = 9, .b = 10 };
55 if (f[0].a != 0 || f[0].b != 0
56 || f[1].a != 7 || f[1].b != 8
57 || f[2].a != 9 || f[2].b != 10)
58 return false;
59 f[0].~T ();
60 f[1].~T ();
61 f[2].~T ();
62 e.deallocate (f, 3);
63 auto g = a.allocate (3);
64 new (g) int[] {1, 2, 3};
65 if (g[0] != 1 || g[1] != 2 || g[2] != 3)
66 return false;
67 new (g) int[] {4, 5};
68 if (g[0] != 4 || g[1] != 5)
69 return false;
70 a.deallocate (g, 3);
71 return true;
72 }
73
74 static_assert (foo ());