28bfce84df88d57705b9fd7326b1d6b89a698332
[binutils-gdb.git] / gdb / unittests / optional / cons / copy.cc
1 // Copyright (C) 2013-2019 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 namespace cons_copy {
19
20 struct tracker
21 {
22 tracker(int value) : value(value) { ++count; }
23 ~tracker() { --count; }
24
25 tracker(tracker const& other) : value(other.value) { ++count; }
26 tracker(tracker&& other) : value(other.value)
27 {
28 other.value = -1;
29 ++count;
30 }
31
32 tracker& operator=(tracker const&) = default;
33 tracker& operator=(tracker&&) = default;
34
35 int value;
36
37 static int count;
38 };
39
40 int tracker::count = 0;
41
42 struct exception { };
43
44 struct throwing_copy
45 {
46 throwing_copy() = default;
47 throwing_copy(throwing_copy const&) { throw exception {}; }
48 };
49
50 void test()
51 {
52 // [20.5.4.1] Constructors
53
54 {
55 gdb::optional<long> o;
56 auto copy = o;
57 VERIFY( !copy );
58 VERIFY( !o );
59 }
60
61 {
62 const long val = 0x1234ABCD;
63 gdb::optional<long> o { gdb::in_place, val};
64 auto copy = o;
65 VERIFY( copy );
66 VERIFY( *copy == val );
67 #ifndef GDB_OPTIONAL
68 VERIFY( o && o == val );
69 #endif
70 }
71
72 {
73 gdb::optional<tracker> o;
74 auto copy = o;
75 VERIFY( !copy );
76 VERIFY( tracker::count == 0 );
77 VERIFY( !o );
78 }
79
80 {
81 gdb::optional<tracker> o { gdb::in_place, 333 };
82 auto copy = o;
83 VERIFY( copy );
84 VERIFY( copy->value == 333 );
85 VERIFY( tracker::count == 2 );
86 VERIFY( o && o->value == 333 );
87 }
88
89 enum outcome { nothrow, caught, bad_catch };
90
91 {
92 outcome result = nothrow;
93 gdb::optional<throwing_copy> o;
94
95 try
96 {
97 auto copy = o;
98 }
99 catch(exception const&)
100 { result = caught; }
101 catch(...)
102 { result = bad_catch; }
103
104 VERIFY( result == nothrow );
105 }
106
107 {
108 outcome result = nothrow;
109 gdb::optional<throwing_copy> o { gdb::in_place };
110
111 try
112 {
113 auto copy = o;
114 }
115 catch(exception const&)
116 { result = caught; }
117 catch(...)
118 { result = bad_catch; }
119
120 VERIFY( result == caught );
121 }
122
123 VERIFY( tracker::count == 0 );
124 }
125
126 } // namespace cons_copy