no_destructor.h 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. // absl::NoDestructor<T> is useful when when a variable has static storage
  25. // duration but its type has a non-trivial destructor. Global constructors are
  26. // not recommended because of the C++'s static initialization order fiasco (See
  27. // https://en.cppreference.com/w/cpp/language/siof). Global destructors are not
  28. // allowed due to similar concerns about destruction ordering. Using
  29. // absl::NoDestructor<T> as a function-local static prevents both of these
  30. // issues.
  31. //
  32. // See below for complete details.
  33. #ifndef ABSL_BASE_NO_DESTRUCTOR_H_
  34. #define ABSL_BASE_NO_DESTRUCTOR_H_
  35. #include <new>
  36. #include <type_traits>
  37. #include <utility>
  38. #include "absl/base/config.h"
  39. #include "absl/base/nullability.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. // ideally as 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. // Additionally, NoDestructor<T> provides the following benefits:
  59. //
  60. // * Never calls T's destructor for the object
  61. // * If the object is a function-local static variable, the type can be
  62. // lazily constructed.
  63. //
  64. // An object of type NoDestructor<T> is "trivially destructible" in the notion
  65. // that its destructor is never run.
  66. //
  67. // Usage as Function Scope Static Variables
  68. //
  69. // Function static objects will be lazily initialized within static storage:
  70. //
  71. // // Function scope.
  72. // const std::string& MyString() {
  73. // static const absl::NoDestructor<std::string> x("foo");
  74. // return *x;
  75. // }
  76. //
  77. // For function static variables, NoDestructor avoids heap allocation and can be
  78. // inlined in static storage, resulting in exactly-once, thread-safe
  79. // construction of an object, and very fast access thereafter (the cost is a few
  80. // extra cycles).
  81. //
  82. // Using NoDestructor<T> in this manner is generally better than other patterns
  83. // which require pointer chasing:
  84. //
  85. // // Prefer using absl::NoDestructor<T> instead for the static variable.
  86. // const std::string& MyString() {
  87. // static const std::string* x = new std::string("foo");
  88. // return *x;
  89. // }
  90. //
  91. // Usage as Global Static Variables
  92. //
  93. // NoDestructor<T> allows declaration of a global object of type T that has a
  94. // non-trivial destructor since its destructor is never run. However, such
  95. // objects still need to worry about initialization order, so such use is not
  96. // recommended, strongly discouraged by the Google C++ Style Guide, and outright
  97. // banned in Chromium.
  98. // See https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables
  99. //
  100. // // Global or namespace scope.
  101. // absl::NoDestructor<MyRegistry> reg{"foo", "bar", 8008};
  102. //
  103. // Note that if your object already has a trivial destructor, you don't need to
  104. // use NoDestructor<T>.
  105. //
  106. template <typename T>
  107. class NoDestructor {
  108. public:
  109. // Forwards arguments to the T's constructor: calls T(args...).
  110. template <typename... Ts,
  111. // Disable this overload when it might collide with copy/move.
  112. typename std::enable_if<!std::is_same<void(std::decay_t<Ts>&...),
  113. void(NoDestructor&)>::value,
  114. int>::type = 0>
  115. explicit constexpr NoDestructor(Ts&&... args)
  116. : impl_(std::forward<Ts>(args)...) {}
  117. // Forwards copy and move construction for T. Enables usage like this:
  118. // static NoDestructor<std::array<string, 3>> x{{{"1", "2", "3"}}};
  119. // static NoDestructor<std::vector<int>> x{{1, 2, 3}};
  120. explicit constexpr NoDestructor(const T& x) : impl_(x) {}
  121. explicit constexpr NoDestructor(T&& x)
  122. : impl_(std::move(x)) {}
  123. // No copying.
  124. NoDestructor(const NoDestructor&) = delete;
  125. NoDestructor& operator=(const NoDestructor&) = delete;
  126. // Pretend to be a smart pointer to T with deep constness.
  127. // Never returns a null pointer.
  128. T& operator*() { return *get(); }
  129. absl::Nonnull<T*> operator->() { return get(); }
  130. absl::Nonnull<T*> get() { return impl_.get(); }
  131. const T& operator*() const { return *get(); }
  132. absl::Nonnull<const T*> operator->() const { return get(); }
  133. absl::Nonnull<const T*> get() const { return impl_.get(); }
  134. private:
  135. class DirectImpl {
  136. public:
  137. template <typename... Args>
  138. explicit constexpr DirectImpl(Args&&... args)
  139. : value_(std::forward<Args>(args)...) {}
  140. absl::Nonnull<const T*> get() const { return &value_; }
  141. absl::Nonnull<T*> get() { return &value_; }
  142. private:
  143. T value_;
  144. };
  145. class PlacementImpl {
  146. public:
  147. template <typename... Args>
  148. explicit PlacementImpl(Args&&... args) {
  149. new (&space_) T(std::forward<Args>(args)...);
  150. }
  151. absl::Nonnull<const T*> get() const {
  152. return Launder(reinterpret_cast<const T*>(&space_));
  153. }
  154. absl::Nonnull<T*> get() { return Launder(reinterpret_cast<T*>(&space_)); }
  155. private:
  156. template <typename P>
  157. static absl::Nonnull<P*> Launder(absl::Nonnull<P*> p) {
  158. #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606L
  159. return std::launder(p);
  160. #elif ABSL_HAVE_BUILTIN(__builtin_launder)
  161. return __builtin_launder(p);
  162. #else
  163. // When `std::launder` or equivalent are not available, we rely on
  164. // undefined behavior, which works as intended on Abseil's officially
  165. // supported platforms as of Q3 2023.
  166. #if defined(__GNUC__) && !defined(__clang__)
  167. #pragma GCC diagnostic push
  168. #pragma GCC diagnostic ignored "-Wstrict-aliasing"
  169. #endif
  170. return p;
  171. #if defined(__GNUC__) && !defined(__clang__)
  172. #pragma GCC diagnostic pop
  173. #endif
  174. #endif
  175. }
  176. alignas(T) unsigned char space_[sizeof(T)];
  177. };
  178. // If the object is trivially destructible we use a member directly to avoid
  179. // potential once-init runtime initialization. It somewhat defeats the
  180. // purpose of NoDestructor in this case, but this makes the class more
  181. // friendly to generic code.
  182. std::conditional_t<std::is_trivially_destructible<T>::value, DirectImpl,
  183. PlacementImpl>
  184. impl_;
  185. };
  186. #ifdef ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION
  187. // Provide 'Class Template Argument Deduction': the type of NoDestructor's T
  188. // will be the same type as the argument passed to NoDestructor's constructor.
  189. template <typename T>
  190. NoDestructor(T) -> NoDestructor<T>;
  191. #endif // ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION
  192. ABSL_NAMESPACE_END
  193. } // namespace absl
  194. #endif // ABSL_BASE_NO_DESTRUCTOR_H_