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 | // UNSUPPORTED: c++03, c++11, c++14 |
10 | |
11 | // <any> |
12 | |
13 | // any(any const &); |
14 | |
15 | #include <any> |
16 | #include <cassert> |
17 | |
18 | #include "any_helpers.h" |
19 | #include "count_new.h" |
20 | #include "test_macros.h" |
21 | |
22 | template <class Type> |
23 | void test_copy_throws() { |
24 | #if !defined(TEST_HAS_NO_EXCEPTIONS) |
25 | assert(Type::count == 0); |
26 | { |
27 | const std::any a = Type(42); |
28 | assert(Type::count == 1); |
29 | try { |
30 | const std::any a2(a); |
31 | assert(false); |
32 | } catch (my_any_exception const &) { |
33 | // do nothing |
34 | } catch (...) { |
35 | assert(false); |
36 | } |
37 | assert(Type::count == 1); |
38 | assertContains<Type>(a, 42); |
39 | } |
40 | assert(Type::count == 0); |
41 | #endif |
42 | } |
43 | |
44 | void test_copy_empty() { |
45 | DisableAllocationGuard g; ((void)g); // No allocations should occur. |
46 | std::any a1; |
47 | std::any a2(a1); |
48 | |
49 | assertEmpty(a1); |
50 | assertEmpty(a2); |
51 | } |
52 | |
53 | template <class Type> |
54 | void test_copy() |
55 | { |
56 | // Copying small types should not perform any allocations. |
57 | DisableAllocationGuard g(isSmallType<Type>()); ((void)g); |
58 | assert(Type::count == 0); |
59 | Type::reset(); |
60 | { |
61 | std::any a = Type(42); |
62 | assert(Type::count == 1); |
63 | assert(Type::copied == 0); |
64 | |
65 | std::any a2(a); |
66 | |
67 | assert(Type::copied == 1); |
68 | assert(Type::count == 2); |
69 | assertContains<Type>(a, 42); |
70 | assertContains<Type>(a2, 42); |
71 | |
72 | // Modify a and check that a2 is unchanged |
73 | modifyValue<Type>(a, -1); |
74 | assertContains<Type>(a, -1); |
75 | assertContains<Type>(a2, 42); |
76 | |
77 | // modify a2 and check that a is unchanged |
78 | modifyValue<Type>(a2, 999); |
79 | assertContains<Type>(a, -1); |
80 | assertContains<Type>(a2, 999); |
81 | |
82 | // clear a and check that a2 is unchanged |
83 | a.reset(); |
84 | assertEmpty(a); |
85 | assertContains<Type>(a2, 999); |
86 | } |
87 | assert(Type::count == 0); |
88 | } |
89 | |
90 | int main(int, char**) { |
91 | test_copy<small>(); |
92 | test_copy<large>(); |
93 | test_copy_empty(); |
94 | test_copy_throws<small_throws_on_copy>(); |
95 | test_copy_throws<large_throws_on_copy>(); |
96 | |
97 | return 0; |
98 | } |
99 | |