]> git.ipfire.org Git - thirdparty/gcc.git/blob - libstdc++-v3/testsuite/20_util/polymorphic_allocator/allocate_object.cc
54f1004b4f3db8123d1cd6ef4ab420f687314b73
[thirdparty/gcc.git] / libstdc++-v3 / testsuite / 20_util / polymorphic_allocator / allocate_object.cc
1 // Copyright (C) 2019-2023 Free Software Foundation, Inc.
2 //
3 // This file is part of the GNU ISO C++ Library. This library is free
4 // software; you can redistribute it and/or modify it under the
5 // terms of the GNU General Public License as published by the
6 // Free Software Foundation; either version 3, or (at your option)
7 // any later version.
8
9 // This library is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13
14 // You should have received a copy of the GNU General Public License along
15 // with this library; see the file COPYING3. If not see
16 // <http://www.gnu.org/licenses/>.
17
18 // { dg-do run { target c++20 } }
19
20 #include <memory_resource>
21 #include <cstring>
22 #include <testsuite_hooks.h>
23 #include <testsuite_allocator.h>
24
25 void
26 test01()
27 {
28 __gnu_test::memory_resource res;
29 std::pmr::polymorphic_allocator<> alloc(&res);
30 static_assert( std::is_same_v<decltype(alloc)::value_type, std::byte> );
31
32 void* p = alloc.allocate_bytes(100);
33 VERIFY( res.number_of_active_allocations() == 1 );
34 alloc.deallocate_bytes(p, 100);
35 VERIFY( res.number_of_active_allocations() == 0 );
36 p = alloc.allocate_bytes(100, 64);
37 VERIFY( res.number_of_active_allocations() == 1 );
38 alloc.deallocate_bytes(p, 100, 64);
39 VERIFY( res.number_of_active_allocations() == 0 );
40
41 int* p1 = alloc.allocate_object<int>();
42 int* p2 = alloc.allocate_object<int>(2);
43 struct X { double d[10]; };
44 X* px = alloc.allocate_object<X>(20);
45 VERIFY( res.number_of_active_allocations() == 3 );
46
47 alloc.deallocate_object(p1);
48 alloc.deallocate_object(p2, 2);
49 alloc.deallocate_object(px, 20);
50 VERIFY( res.number_of_active_allocations() == 0 );
51
52 struct Y {
53 Y(int i, const char* s, bool* alive)
54 : i(i), s(s), alive(alive)
55 { *alive = true; }
56
57 ~Y() { *alive = false; }
58
59 int i;
60 const char* s;
61 bool* alive;
62 };
63
64 bool alive = false;
65 Y* py = alloc.new_object<Y>(1, "two", &alive);
66 VERIFY( alive );
67 VERIFY( py->i == 1 );
68 VERIFY( std::strcmp(py->s, "two") == 0 );
69 VERIFY( res.number_of_active_allocations() == 1 );
70
71 alloc.delete_object(py);
72 VERIFY( alive == false );
73 }
74
75 int
76 main()
77 {
78 test01();
79 }