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