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