]> gcc.gnu.org Git - gcc.git/blob - libstdc++-v3/include/std/any
Make any's copy assignment operator exception-safe,
[gcc.git] / libstdc++-v3 / include / std / any
1 // <any> -*- C++ -*-
2
3 // Copyright (C) 2014-2016 Free Software Foundation, Inc.
4 //
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
9 // any later version.
10
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
19
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 // <http://www.gnu.org/licenses/>.
24
25 /** @file include/any
26 * This is a Standard C++ Library header.
27 */
28
29 #ifndef _GLIBCXX_ANY
30 #define _GLIBCXX_ANY 1
31
32 #pragma GCC system_header
33
34 #if __cplusplus <= 201402L
35 # include <bits/c++17_warning.h>
36 #else
37
38 #include <typeinfo>
39 #include <new>
40 #include <utility>
41 #include <type_traits>
42
43 namespace std _GLIBCXX_VISIBILITY(default)
44 {
45 _GLIBCXX_BEGIN_NAMESPACE_VERSION
46
47 /**
48 * @addtogroup utilities
49 * @{
50 */
51
52 /**
53 * @brief Exception class thrown by a failed @c any_cast
54 * @ingroup exceptions
55 */
56 class bad_any_cast : public bad_cast
57 {
58 public:
59 virtual const char* what() const noexcept { return "bad any_cast"; }
60 };
61
62 [[gnu::noreturn]] inline void __throw_bad_any_cast()
63 {
64 #if __cpp_exceptions
65 throw bad_any_cast{};
66 #else
67 __builtin_abort();
68 #endif
69 }
70
71 /**
72 * @brief A type-safe container of any type.
73 *
74 * An @c any object's state is either empty or it stores a contained object
75 * of CopyConstructible type.
76 */
77 class any
78 {
79 // Holds either pointer to a heap object or the contained object itself.
80 union _Storage
81 {
82 constexpr _Storage() : _M_ptr{nullptr} {}
83
84 // Prevent trivial copies of this type, buffer might hold a non-POD.
85 _Storage(const _Storage&) = delete;
86 _Storage& operator=(const _Storage&) = delete;
87
88 void* _M_ptr;
89 aligned_storage<sizeof(_M_ptr), alignof(void*)>::type _M_buffer;
90 };
91
92 template<typename _Tp, typename _Safe = is_nothrow_move_constructible<_Tp>,
93 bool _Fits = (sizeof(_Tp) <= sizeof(_Storage))
94 && (alignof(_Tp) <= alignof(_Storage))>
95 using _Internal = std::integral_constant<bool, _Safe::value && _Fits>;
96
97 template<typename _Tp>
98 struct _Manager_internal; // uses small-object optimization
99
100 template<typename _Tp>
101 struct _Manager_external; // creates contained object on the heap
102
103 template<typename _Tp>
104 using _Manager = conditional_t<_Internal<_Tp>::value,
105 _Manager_internal<_Tp>,
106 _Manager_external<_Tp>>;
107
108 template<typename _Tp, typename _Decayed = decay_t<_Tp>>
109 using _Decay = enable_if_t<!is_same<_Decayed, any>::value, _Decayed>;
110
111 public:
112 // construct/destruct
113
114 /// Default constructor, creates an empty object.
115 constexpr any() noexcept : _M_manager(nullptr) { }
116
117 /// Copy constructor, copies the state of @p __other
118 any(const any& __other)
119 {
120 if (!__other.has_value())
121 _M_manager = nullptr;
122 else
123 {
124 _Arg __arg;
125 __arg._M_any = this;
126 __other._M_manager(_Op_clone, &__other, &__arg);
127 }
128 }
129
130 /**
131 * @brief Move constructor, transfer the state from @p __other
132 *
133 * @post @c !__other.has_value() (this postcondition is a GNU extension)
134 */
135 any(any&& __other) noexcept
136 {
137 if (!__other.has_value())
138 _M_manager = nullptr;
139 else
140 {
141 _Arg __arg;
142 __arg._M_any = this;
143 __other._M_manager(_Op_xfer, &__other, &__arg);
144 }
145 }
146
147 template <typename _Tp, typename... _Args>
148 using __any_constructible_t =
149 enable_if_t<__and_<is_copy_constructible<_Tp>,
150 is_constructible<_Tp, _Args...>>::value,
151 bool>;
152
153 /// Construct with a copy of @p __value as the contained object.
154 template <typename _ValueType, typename _Tp = _Decay<_ValueType>,
155 typename _Mgr = _Manager<_Tp>,
156 __any_constructible_t<_Tp, _ValueType&&> = true,
157 enable_if_t<!__is_in_place_type<_ValueType>::value, bool> = true>
158 any(_ValueType&& __value)
159 : _M_manager(&_Mgr::_S_manage)
160 {
161 _Mgr::_S_create(_M_storage, std::forward<_ValueType>(__value));
162 }
163
164 /// Construct with a copy of @p __value as the contained object.
165 template <typename _ValueType, typename _Tp = _Decay<_ValueType>,
166 typename _Mgr = _Manager<_Tp>,
167 enable_if_t<__and_<is_copy_constructible<_Tp>,
168 __not_<is_constructible<_Tp, _ValueType&&>>,
169 __not_<__is_in_place_type<_ValueType>>>::value,
170 bool> = false>
171 any(_ValueType&& __value)
172 : _M_manager(&_Mgr::_S_manage)
173 {
174 _Mgr::_S_create(_M_storage, __value);
175 }
176
177 /// Construct with an object created from @p __args as the contained object.
178 template <typename _ValueType, typename... _Args,
179 typename _Tp = _Decay<_ValueType>,
180 typename _Mgr = _Manager<_Tp>,
181 __any_constructible_t<_Tp, _Args&&...> = false>
182 explicit
183 any(in_place_type_t<_ValueType>, _Args&&... __args)
184 : _M_manager(&_Mgr::_S_manage)
185 {
186 _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...);
187 }
188
189 /// Construct with an object created from @p __il and @p __args as
190 /// the contained object.
191 template <typename _ValueType, typename _Up, typename... _Args,
192 typename _Tp = _Decay<_ValueType>,
193 typename _Mgr = _Manager<_Tp>,
194 __any_constructible_t<_Tp, initializer_list<_Up>,
195 _Args&&...> = false>
196 explicit
197 any(in_place_type_t<_ValueType>,
198 initializer_list<_Up> __il, _Args&&... __args)
199 : _M_manager(&_Mgr::_S_manage)
200 {
201 _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...);
202 }
203
204 /// Destructor, calls @c reset()
205 ~any() { reset(); }
206
207 // assignments
208
209 /// Copy the state of another object.
210 any& operator=(const any& __rhs)
211 {
212 *this = any(__rhs);
213 return *this;
214 }
215
216 /**
217 * @brief Move assignment operator
218 *
219 * @post @c !__rhs.has_value() (not guaranteed for other implementations)
220 */
221 any& operator=(any&& __rhs) noexcept
222 {
223 if (!__rhs.has_value())
224 reset();
225 else if (this != &__rhs)
226 {
227 reset();
228 _Arg __arg;
229 __arg._M_any = this;
230 __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
231 }
232 return *this;
233 }
234
235 /// Store a copy of @p __rhs as the contained object.
236 template<typename _ValueType,
237 typename _Tp = _Decay<_ValueType>>
238 enable_if_t<is_copy_constructible<_Tp>::value, any&>
239 operator=(_ValueType&& __rhs)
240 {
241 *this = any(std::forward<_ValueType>(__rhs));
242 return *this;
243 }
244
245 /// Emplace with an object created from @p __args as the contained object.
246 template <typename _ValueType, typename... _Args,
247 typename _Tp = _Decay<_ValueType>,
248 typename _Mgr = _Manager<_Tp>,
249 __any_constructible_t<_Tp, _Args&&...> = false>
250 void emplace(_Args&&... __args)
251 {
252 reset();
253 _M_manager = &_Mgr::_S_manage;
254 _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...);
255 }
256
257 /// Emplace with an object created from @p __il and @p __args as
258 /// the contained object.
259 template <typename _ValueType, typename _Up, typename... _Args,
260 typename _Tp = _Decay<_ValueType>,
261 typename _Mgr = _Manager<_Tp>,
262 __any_constructible_t<_Tp, initializer_list<_Up>,
263 _Args&&...> = false>
264 void emplace(initializer_list<_Up> __il, _Args&&... __args)
265 {
266 reset();
267 _M_manager = &_Mgr::_S_manage;
268 _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...);
269 }
270
271 // modifiers
272
273 /// If not empty, destroy the contained object.
274 void reset() noexcept
275 {
276 if (has_value())
277 {
278 _M_manager(_Op_destroy, this, nullptr);
279 _M_manager = nullptr;
280 }
281 }
282
283 /// Exchange state with another object.
284 void swap(any& __rhs) noexcept
285 {
286 if (!has_value() && !__rhs.has_value())
287 return;
288
289 if (has_value() && __rhs.has_value())
290 {
291 if (this == &__rhs)
292 return;
293
294 any __tmp;
295 _Arg __arg;
296 __arg._M_any = &__tmp;
297 __rhs._M_manager(_Op_xfer, &__rhs, &__arg);
298 __arg._M_any = &__rhs;
299 _M_manager(_Op_xfer, this, &__arg);
300 __arg._M_any = this;
301 __tmp._M_manager(_Op_xfer, &__tmp, &__arg);
302 }
303 else
304 {
305 any* __empty = !has_value() ? this : &__rhs;
306 any* __full = !has_value() ? &__rhs : this;
307 _Arg __arg;
308 __arg._M_any = __empty;
309 __full->_M_manager(_Op_xfer, __full, &__arg);
310 }
311 }
312
313 // observers
314
315 /// Reports whether there is a contained object or not.
316 bool has_value() const noexcept { return _M_manager != nullptr; }
317
318 #if __cpp_rtti
319 /// The @c typeid of the contained object, or @c typeid(void) if empty.
320 const type_info& type() const noexcept
321 {
322 if (!has_value())
323 return typeid(void);
324 _Arg __arg;
325 _M_manager(_Op_get_type_info, this, &__arg);
326 return *__arg._M_typeinfo;
327 }
328 #endif
329
330 template<typename _Tp>
331 static constexpr bool __is_valid_cast()
332 { return __or_<is_reference<_Tp>, is_copy_constructible<_Tp>>::value; }
333
334 private:
335 enum _Op {
336 _Op_access, _Op_get_type_info, _Op_clone, _Op_destroy, _Op_xfer
337 };
338
339 union _Arg
340 {
341 void* _M_obj;
342 const std::type_info* _M_typeinfo;
343 any* _M_any;
344 };
345
346 void (*_M_manager)(_Op, const any*, _Arg*);
347 _Storage _M_storage;
348
349 template<typename _Tp>
350 friend void* __any_caster(const any* __any);
351
352 // Manage in-place contained object.
353 template<typename _Tp>
354 struct _Manager_internal
355 {
356 static void
357 _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
358
359 template<typename _Up>
360 static void
361 _S_create(_Storage& __storage, _Up&& __value)
362 {
363 void* __addr = &__storage._M_buffer;
364 ::new (__addr) _Tp(std::forward<_Up>(__value));
365 }
366
367 template<typename... _Args>
368 static void
369 _S_create(_Storage& __storage, _Args&&... __args)
370 {
371 void* __addr = &__storage._M_buffer;
372 ::new (__addr) _Tp(std::forward<_Args>(__args)...);
373 }
374 };
375
376 // Manage external contained object.
377 template<typename _Tp>
378 struct _Manager_external
379 {
380 static void
381 _S_manage(_Op __which, const any* __anyp, _Arg* __arg);
382
383 template<typename _Up>
384 static void
385 _S_create(_Storage& __storage, _Up&& __value)
386 {
387 __storage._M_ptr = new _Tp(std::forward<_Up>(__value));
388 }
389 template<typename... _Args>
390 static void
391 _S_create(_Storage& __storage, _Args&&... __args)
392 {
393 __storage._M_ptr = new _Tp(std::forward<_Args>(__args)...);
394 }
395 };
396 };
397
398 /// Exchange the states of two @c any objects.
399 inline void swap(any& __x, any& __y) noexcept { __x.swap(__y); }
400
401 /// Create an any holding a @c _Tp constructed from @c __args.
402 template <typename _Tp, typename... _Args>
403 any make_any(_Args&&... __args)
404 {
405 return any(in_place<_Tp>, std::forward<_Args>(__args)...);
406 }
407
408 /// Create an any holding a @c _Tp constructed from @c __il and @c __args.
409 template <typename _Tp, typename _Up, typename... _Args>
410 any make_any(initializer_list<_Up> __il, _Args&&... __args)
411 {
412 return any(in_place<_Tp>, __il, std::forward<_Args>(__args)...);
413 }
414
415 /**
416 * @brief Access the contained object.
417 *
418 * @tparam _ValueType A const-reference or CopyConstructible type.
419 * @param __any The object to access.
420 * @return The contained object.
421 * @throw bad_any_cast If <code>
422 * __any.type() != typeid(remove_reference_t<_ValueType>)
423 * </code>
424 */
425 template<typename _ValueType>
426 inline _ValueType any_cast(const any& __any)
427 {
428 static_assert(any::__is_valid_cast<_ValueType>(),
429 "Template argument must be a reference or CopyConstructible type");
430 auto __p = any_cast<add_const_t<remove_reference_t<_ValueType>>>(&__any);
431 if (__p)
432 return *__p;
433 __throw_bad_any_cast();
434 }
435
436 /**
437 * @brief Access the contained object.
438 *
439 * @tparam _ValueType A reference or CopyConstructible type.
440 * @param __any The object to access.
441 * @return The contained object.
442 * @throw bad_any_cast If <code>
443 * __any.type() != typeid(remove_reference_t<_ValueType>)
444 * </code>
445 *
446 * @{
447 */
448 template<typename _ValueType>
449 inline _ValueType any_cast(any& __any)
450 {
451 static_assert(any::__is_valid_cast<_ValueType>(),
452 "Template argument must be a reference or CopyConstructible type");
453 auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
454 if (__p)
455 return *__p;
456 __throw_bad_any_cast();
457 }
458
459 template<typename _ValueType,
460 typename enable_if<!is_move_constructible<_ValueType>::value
461 || is_lvalue_reference<_ValueType>::value,
462 bool>::type = true>
463 inline _ValueType any_cast(any&& __any)
464 {
465 static_assert(any::__is_valid_cast<_ValueType>(),
466 "Template argument must be a reference or CopyConstructible type");
467 auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
468 if (__p)
469 return *__p;
470 __throw_bad_any_cast();
471 }
472
473 template<typename _ValueType,
474 typename enable_if<is_move_constructible<_ValueType>::value
475 && !is_lvalue_reference<_ValueType>::value,
476 bool>::type = false>
477 inline _ValueType any_cast(any&& __any)
478 {
479 static_assert(any::__is_valid_cast<_ValueType>(),
480 "Template argument must be a reference or CopyConstructible type");
481 auto __p = any_cast<remove_reference_t<_ValueType>>(&__any);
482 if (__p)
483 return std::move(*__p);
484 __throw_bad_any_cast();
485 }
486 // @}
487
488 template<typename _Tp>
489 void* __any_caster(const any* __any)
490 {
491 if (__any->_M_manager != &any::_Manager<decay_t<_Tp>>::_S_manage)
492 return nullptr;
493 any::_Arg __arg;
494 __any->_M_manager(any::_Op_access, __any, &__arg);
495 return __arg._M_obj;
496 }
497
498 /**
499 * @brief Access the contained object.
500 *
501 * @tparam _ValueType The type of the contained object.
502 * @param __any A pointer to the object to access.
503 * @return The address of the contained object if <code>
504 * __any != nullptr && __any.type() == typeid(_ValueType)
505 * </code>, otherwise a null pointer.
506 *
507 * @{
508 */
509 template<typename _ValueType>
510 inline const _ValueType* any_cast(const any* __any) noexcept
511 {
512 if (__any)
513 return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
514 return nullptr;
515 }
516
517 template<typename _ValueType>
518 inline _ValueType* any_cast(any* __any) noexcept
519 {
520 if (__any)
521 return static_cast<_ValueType*>(__any_caster<_ValueType>(__any));
522 return nullptr;
523 }
524 // @}
525
526 template<typename _Tp>
527 void
528 any::_Manager_internal<_Tp>::
529 _S_manage(_Op __which, const any* __any, _Arg* __arg)
530 {
531 // The contained object is in _M_storage._M_buffer
532 auto __ptr = reinterpret_cast<const _Tp*>(&__any->_M_storage._M_buffer);
533 switch (__which)
534 {
535 case _Op_access:
536 __arg->_M_obj = const_cast<_Tp*>(__ptr);
537 break;
538 case _Op_get_type_info:
539 #if __cpp_rtti
540 __arg->_M_typeinfo = &typeid(_Tp);
541 #endif
542 break;
543 case _Op_clone:
544 ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp(*__ptr);
545 __arg->_M_any->_M_manager = __any->_M_manager;
546 break;
547 case _Op_destroy:
548 __ptr->~_Tp();
549 break;
550 case _Op_xfer:
551 ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp
552 (std::move(*const_cast<_Tp*>(__ptr)));
553 __ptr->~_Tp();
554 __arg->_M_any->_M_manager = __any->_M_manager;
555 const_cast<any*>(__any)->_M_manager = nullptr;
556 break;
557 }
558 }
559
560 template<typename _Tp>
561 void
562 any::_Manager_external<_Tp>::
563 _S_manage(_Op __which, const any* __any, _Arg* __arg)
564 {
565 // The contained object is *_M_storage._M_ptr
566 auto __ptr = static_cast<const _Tp*>(__any->_M_storage._M_ptr);
567 switch (__which)
568 {
569 case _Op_access:
570 __arg->_M_obj = const_cast<_Tp*>(__ptr);
571 break;
572 case _Op_get_type_info:
573 #if __cpp_rtti
574 __arg->_M_typeinfo = &typeid(_Tp);
575 #endif
576 break;
577 case _Op_clone:
578 __arg->_M_any->_M_storage._M_ptr = new _Tp(*__ptr);
579 __arg->_M_any->_M_manager = __any->_M_manager;
580 break;
581 case _Op_destroy:
582 delete __ptr;
583 break;
584 case _Op_xfer:
585 __arg->_M_any->_M_storage._M_ptr = __any->_M_storage._M_ptr;
586 __arg->_M_any->_M_manager = __any->_M_manager;
587 const_cast<any*>(__any)->_M_manager = nullptr;
588 break;
589 }
590 }
591
592 /// @}
593
594 _GLIBCXX_END_NAMESPACE_VERSION
595 } // namespace std
596
597 #endif // C++14
598
599 #endif // _GLIBCXX_ANY
This page took 0.073367 seconds and 6 git commands to generate.