Debian Codegraph @

libstdc++-v3/testsuite/20_util/move_only_function/move.cc

raw
1 // { dg-do run { target c++23 } }
2 // { dg-require-effective-target hosted }
3
4 #include <functional>
5 #include <testsuite_hooks.h>
6
7 using std::move_only_function;
8
9 void
10 test01()
11 {
12 // Small type with non-throwing move constructor. Not allocated on the heap.
13 struct F
14 {
15 F() = default;
16 F(const F& f) : counters(f.counters) { ++counters.copy; }
17 F(F&& f) noexcept : counters(f.counters) { ++counters.move; }
18
19 F& operator=(F&&) = delete;
20
21 struct Counters
22 {
23 int copy = 0;
24 int move = 0;
25 } counters;
26
27 const Counters& operator()() const { return counters; }
28 };
29
30 F f;
31 std::move_only_function<const F::Counters&() const> m1(f);
32 VERIFY( m1().copy == 1 );
33 VERIFY( m1().move == 0 );
34
35 // This will move construct a new target object and destroy the old one:
36 auto m2 = std::move(m1);
37 VERIFY( m1 == nullptr && m2 != nullptr );
38 VERIFY( m2().copy == 1 );
39 VERIFY( m2().move == 1 );
40
41 m1 = std::move(m2);
42 VERIFY( m1 != nullptr && m2 == nullptr );
43 VERIFY( m1().copy == 1 );
44 VERIFY( m1().move == 2 );
45
46 m2 = std::move(f);
47 VERIFY( m2().copy == 0 );
48 VERIFY( m2().move == 2 ); // Move construct target object, then swap into m2.
49 const int moves = m1().move + m2().move;
50 // This will do three moves:
51 swap(m1, m2);
52 VERIFY( m1().copy == 0 );
53 VERIFY( m2().copy == 1 );
54 VERIFY( (m1().move + m2().move) == (moves + 3) );
55 }
56
57 void
58 test02()
59 {
60 // Move constructor is potentially throwing. Allocated on the heap.
61 struct F
62 {
63 F() = default;
64 F(const F& f) noexcept : counters(f.counters) { ++counters.copy; }
65 F(F&& f) noexcept(false) : counters(f.counters) { ++counters.move; }
66
67 F& operator=(F&&) = delete;
68
69 struct Counters
70 {
71 int copy = 0;
72 int move = 0;
73 } counters;
74
75 Counters operator()() const noexcept { return counters; }
76 };
77
78 F f;
79 std::move_only_function<F::Counters() const> m1(f);
80 VERIFY( m1().copy == 1 );
81 VERIFY( m1().move == 0 );
82
83 // The target object is on the heap so this just moves a pointer:
84 auto m2 = std::move(m1);
85 VERIFY( m1 == nullptr && m2 != nullptr );
86 VERIFY( m2().copy == 1 );
87 VERIFY( m2().move == 0 );
88
89 m1 = std::move(m2);
90 VERIFY( m1 != nullptr && m2 == nullptr );
91 VERIFY( m1().copy == 1 );
92 VERIFY( m1().move == 0 );
93
94 m2 = std::move(f);
95 VERIFY( m2().copy == 0 );
96 VERIFY( m2().move == 1 );
97 const int moves = m1().move + m2().move;
98 // This just swaps the pointers, so no moves:
99 swap(m1, m2);
100 VERIFY( m1().copy == 0 );
101 VERIFY( m2().copy == 1 );
102 VERIFY( (m1().move + m2().move) == moves );
103 }
104
105 int main()
106 {
107 test01();
108 test02();
109 }