no_destroy.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. #ifndef _LIBCPP___UTILITY_NO_DESTROY_H
  9. #define _LIBCPP___UTILITY_NO_DESTROY_H
  10. #include <__config>
  11. #include <__type_traits/is_constant_evaluated.h>
  12. #include <__utility/forward.h>
  13. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  14. # pragma GCC system_header
  15. #endif
  16. _LIBCPP_BEGIN_NAMESPACE_STD
  17. struct __uninitialized_tag {};
  18. // This class stores an object of type _Tp but never destroys it.
  19. //
  20. // This is akin to using __attribute__((no_destroy)), except that it is possible
  21. // to control the lifetime of the object with more flexibility by deciding e.g.
  22. // whether to initialize the object at construction or to defer to a later
  23. // initialization using __emplace.
  24. template <class _Tp>
  25. struct __no_destroy {
  26. _LIBCPP_CONSTEXPR_SINCE_CXX14 _LIBCPP_HIDE_FROM_ABI explicit __no_destroy(__uninitialized_tag) : __dummy_() {
  27. if (__libcpp_is_constant_evaluated()) {
  28. __dummy_ = char();
  29. }
  30. }
  31. _LIBCPP_HIDE_FROM_ABI ~__no_destroy() {
  32. // nothing
  33. }
  34. template <class... _Args>
  35. _LIBCPP_CONSTEXPR _LIBCPP_HIDE_FROM_ABI explicit __no_destroy(_Args&&... __args)
  36. : __obj_(std::forward<_Args>(__args)...) {}
  37. template <class... _Args>
  38. _LIBCPP_CONSTEXPR_SINCE_CXX14 _LIBCPP_HIDE_FROM_ABI _Tp& __emplace(_Args&&... __args) {
  39. new (&__obj_) _Tp(std::forward<_Args>(__args)...);
  40. return __obj_;
  41. }
  42. _LIBCPP_CONSTEXPR_SINCE_CXX14 _LIBCPP_HIDE_FROM_ABI _Tp& __get() { return __obj_; }
  43. _LIBCPP_CONSTEXPR_SINCE_CXX14 _LIBCPP_HIDE_FROM_ABI _Tp const& __get() const { return __obj_; }
  44. private:
  45. union {
  46. _Tp __obj_;
  47. char __dummy_; // so we can initialize a member even with __uninitialized_tag for constexpr-friendliness
  48. };
  49. };
  50. _LIBCPP_END_NAMESPACE_STD
  51. #endif // _LIBCPP___UTILITY_NO_DESTROY_H