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