no_destructor.h 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. // Copyright 2023 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // -----------------------------------------------------------------------------
  16. // File: no_destructor.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This header file defines the absl::NoDestructor<T> wrapper for defining a
  20. // static type that does not need to be destructed upon program exit. Instead,
  21. // such an object survives during program exit (and can be safely accessed at
  22. // any time).
  23. //
  24. // Objects of such type, if constructed safely and under the right conditions,
  25. // provide two main benefits over other alternatives:
  26. //
  27. // * Global objects not normally allowed due to concerns of destruction order
  28. // (i.e. no "complex globals") can be safely allowed, provided that such
  29. // objects can be constant initialized.
  30. // * Function scope static objects can be optimized to avoid heap allocation,
  31. // pointer chasing, and allow lazy construction.
  32. //
  33. // See below for complete details.
  34. #ifndef ABSL_BASE_NO_DESTRUCTOR_H_
  35. #define ABSL_BASE_NO_DESTRUCTOR_H_
  36. #include <new>
  37. #include <type_traits>
  38. #include <utility>
  39. #include "absl/base/config.h"
  40. namespace absl {
  41. ABSL_NAMESPACE_BEGIN
  42. // absl::NoDestructor<T>
  43. //
  44. // NoDestructor<T> is a wrapper around an object of type T that behaves as an
  45. // object of type T but never calls T's destructor. NoDestructor<T> makes it
  46. // safer and/or more efficient to use such objects in static storage contexts:
  47. // as global or function scope static variables.
  48. //
  49. // An instance of absl::NoDestructor<T> has similar type semantics to an
  50. // instance of T:
  51. //
  52. // * Constructs in the same manner as an object of type T through perfect
  53. // forwarding.
  54. // * Provides pointer/reference semantic access to the object of type T via
  55. // `->`, `*`, and `get()`.
  56. // (Note that `const NoDestructor<T>` works like a pointer to const `T`.)
  57. //
  58. // An object of type NoDestructor<T> should be defined in static storage:
  59. // as either a global static object, or as a function scope static variable.
  60. //
  61. // Additionally, NoDestructor<T> provides the following benefits:
  62. //
  63. // * Never calls T's destructor for the object
  64. // * If the object is a function-local static variable, the type can be
  65. // lazily constructed.
  66. //
  67. // An object of type NoDestructor<T> is "trivially destructible" in the notion
  68. // that its destructor is never run. Provided that an object of this type can be
  69. // safely initialized and does not need to be cleaned up on program shutdown,
  70. // NoDestructor<T> allows you to define global static variables, since Google's
  71. // C++ style guide ban on such objects doesn't apply to objects that are
  72. // trivially destructible.
  73. //
  74. // Usage as Global Static Variables
  75. //
  76. // NoDestructor<T> allows declaration of a global object with a non-trivial
  77. // constructor in static storage without needing to add a destructor.
  78. // However, such objects still need to worry about initialization order, so
  79. // such objects should be const initialized:
  80. //
  81. // // Global or namespace scope.
  82. // ABSL_CONST_INIT absl::NoDestructor<MyRegistry> reg{"foo", "bar", 8008};
  83. //
  84. // Note that if your object already has a trivial destructor, you don't need to
  85. // use NoDestructor<T>.
  86. //
  87. // Usage as Function Scope Static Variables
  88. //
  89. // Function static objects will be lazily initialized within static storage:
  90. //
  91. // // Function scope.
  92. // const std::string& MyString() {
  93. // static const absl::NoDestructor<std::string> x("foo");
  94. // return *x;
  95. // }
  96. //
  97. // For function static variables, NoDestructor avoids heap allocation and can be
  98. // inlined in static storage, resulting in exactly-once, thread-safe
  99. // construction of an object, and very fast access thereafter (the cost is a few
  100. // extra cycles).
  101. //
  102. // Using NoDestructor<T> in this manner is generally better than other patterns
  103. // which require pointer chasing:
  104. //
  105. // // Prefer using absl::NoDestructor<T> instead for the static variable.
  106. // const std::string& MyString() {
  107. // static const std::string* x = new std::string("foo");
  108. // return *x;
  109. // }
  110. //
  111. template <typename T>
  112. class NoDestructor {
  113. public:
  114. // Forwards arguments to the T's constructor: calls T(args...).
  115. template <typename... Ts,
  116. // Disable this overload when it might collide with copy/move.
  117. typename std::enable_if<!std::is_same<void(std::decay_t<Ts>&...),
  118. void(NoDestructor&)>::value,
  119. int>::type = 0>
  120. explicit constexpr NoDestructor(Ts&&... args)
  121. : impl_(std::forward<Ts>(args)...) {}
  122. // Forwards copy and move construction for T. Enables usage like this:
  123. // static NoDestructor<std::array<string, 3>> x{{{"1", "2", "3"}}};
  124. // static NoDestructor<std::vector<int>> x{{1, 2, 3}};
  125. explicit constexpr NoDestructor(const T& x) : impl_(x) {}
  126. explicit constexpr NoDestructor(T&& x)
  127. : impl_(std::move(x)) {}
  128. // No copying.
  129. NoDestructor(const NoDestructor&) = delete;
  130. NoDestructor& operator=(const NoDestructor&) = delete;
  131. // Pretend to be a smart pointer to T with deep constness.
  132. // Never returns a null pointer.
  133. T& operator*() { return *get(); }
  134. T* operator->() { return get(); }
  135. T* get() { return impl_.get(); }
  136. const T& operator*() const { return *get(); }
  137. const T* operator->() const { return get(); }
  138. const T* get() const { return impl_.get(); }
  139. private:
  140. class DirectImpl {
  141. public:
  142. template <typename... Args>
  143. explicit constexpr DirectImpl(Args&&... args)
  144. : value_(std::forward<Args>(args)...) {}
  145. const T* get() const { return &value_; }
  146. T* get() { return &value_; }
  147. private:
  148. T value_;
  149. };
  150. class PlacementImpl {
  151. public:
  152. template <typename... Args>
  153. explicit PlacementImpl(Args&&... args) {
  154. new (&space_) T(std::forward<Args>(args)...);
  155. }
  156. const T* get() const {
  157. return Launder(reinterpret_cast<const T*>(&space_));
  158. }
  159. T* get() { return Launder(reinterpret_cast<T*>(&space_)); }
  160. private:
  161. template <typename P>
  162. static P* Launder(P* p) {
  163. #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606L
  164. return std::launder(p);
  165. #elif ABSL_HAVE_BUILTIN(__builtin_launder)
  166. return __builtin_launder(p);
  167. #else
  168. // When `std::launder` or equivalent are not available, we rely on
  169. // undefined behavior, which works as intended on Abseil's officially
  170. // supported platforms as of Q3 2023.
  171. #if defined(__GNUC__) && !defined(__clang__)
  172. #pragma GCC diagnostic push
  173. #pragma GCC diagnostic ignored "-Wstrict-aliasing"
  174. #endif
  175. return p;
  176. #if defined(__GNUC__) && !defined(__clang__)
  177. #pragma GCC diagnostic pop
  178. #endif
  179. #endif
  180. }
  181. alignas(T) unsigned char space_[sizeof(T)];
  182. };
  183. // If the object is trivially destructible we use a member directly to avoid
  184. // potential once-init runtime initialization. It somewhat defeats the
  185. // purpose of NoDestructor in this case, but this makes the class more
  186. // friendly to generic code.
  187. std::conditional_t<std::is_trivially_destructible<T>::value, DirectImpl,
  188. PlacementImpl>
  189. impl_;
  190. };
  191. #ifdef ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION
  192. // Provide 'Class Template Argument Deduction': the type of NoDestructor's T
  193. // will be the same type as the argument passed to NoDestructor's constructor.
  194. template <typename T>
  195. NoDestructor(T) -> NoDestructor<T>;
  196. #endif // ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION
  197. ABSL_NAMESPACE_END
  198. } // namespace absl
  199. #endif // ABSL_BASE_NO_DESTRUCTOR_H_