lazy_instance.h 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. //
  5. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! DEPRECATED !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  6. // Please don't introduce new instances of LazyInstance<T>. Use a function-local
  7. // static of type base::NoDestructor<T> instead:
  8. //
  9. // Factory& Factory::GetInstance() {
  10. // static base::NoDestructor<Factory> instance;
  11. // return *instance;
  12. // }
  13. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  14. //
  15. // The LazyInstance<Type, Traits> class manages a single instance of Type,
  16. // which will be lazily created on the first time it's accessed. This class is
  17. // useful for places you would normally use a function-level static, but you
  18. // need to have guaranteed thread-safety. The Type constructor will only ever
  19. // be called once, even if two threads are racing to create the object. Get()
  20. // and Pointer() will always return the same, completely initialized instance.
  21. // When the instance is constructed it is registered with AtExitManager. The
  22. // destructor will be called on program exit.
  23. //
  24. // LazyInstance is completely thread safe, assuming that you create it safely.
  25. // The class was designed to be POD initialized, so it shouldn't require a
  26. // static constructor. It really only makes sense to declare a LazyInstance as
  27. // a global variable using the LAZY_INSTANCE_INITIALIZER initializer.
  28. //
  29. // LazyInstance is similar to Singleton, except it does not have the singleton
  30. // property. You can have multiple LazyInstance's of the same type, and each
  31. // will manage a unique instance. It also preallocates the space for Type, as
  32. // to avoid allocating the Type instance on the heap. This may help with the
  33. // performance of creating the instance, and reducing heap fragmentation. This
  34. // requires that Type be a complete type so we can determine the size.
  35. //
  36. // Example usage:
  37. // static LazyInstance<MyClass>::Leaky inst = LAZY_INSTANCE_INITIALIZER;
  38. // void SomeMethod() {
  39. // inst.Get().SomeMethod(); // MyClass::SomeMethod()
  40. //
  41. // MyClass* ptr = inst.Pointer();
  42. // ptr->DoDoDo(); // MyClass::DoDoDo
  43. // }
  44. #ifndef BASE_LAZY_INSTANCE_H_
  45. #define BASE_LAZY_INSTANCE_H_
  46. #include <atomic>
  47. #include <new> // For placement new.
  48. #include "base/check_op.h"
  49. #include "base/dcheck_is_on.h"
  50. #include "base/debug/leak_annotations.h"
  51. #include "base/lazy_instance_helpers.h"
  52. #include "base/threading/thread_restrictions.h"
  53. #include "build/build_config.h"
  54. // LazyInstance uses its own struct initializer-list style static
  55. // initialization, which does not require a constructor.
  56. #define LAZY_INSTANCE_INITIALIZER {}
  57. namespace base {
  58. template <typename Type>
  59. struct LazyInstanceTraitsBase {
  60. static Type* New(void* instance) {
  61. DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) & (alignof(Type) - 1), 0u);
  62. // Use placement new to initialize our instance in our preallocated space.
  63. // The parenthesis is very important here to force POD type initialization.
  64. return new (instance) Type();
  65. }
  66. static void CallDestructor(Type* instance) {
  67. // Explicitly call the destructor.
  68. instance->~Type();
  69. }
  70. };
  71. // We pull out some of the functionality into non-templated functions, so we
  72. // can implement the more complicated pieces out of line in the .cc file.
  73. namespace internal {
  74. // This traits class causes destruction the contained Type at process exit via
  75. // AtExitManager. This is probably generally not what you want. Instead, prefer
  76. // Leaky below.
  77. template <typename Type>
  78. struct DestructorAtExitLazyInstanceTraits {
  79. static const bool kRegisterOnExit = true;
  80. #if DCHECK_IS_ON()
  81. static const bool kAllowedToAccessOnNonjoinableThread = false;
  82. #endif
  83. static Type* New(void* instance) {
  84. return LazyInstanceTraitsBase<Type>::New(instance);
  85. }
  86. static void Delete(Type* instance) {
  87. LazyInstanceTraitsBase<Type>::CallDestructor(instance);
  88. }
  89. };
  90. // Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.:
  91. // base::LazyInstance<T>::Leaky my_leaky_lazy_instance;
  92. // instead of:
  93. // base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> >
  94. // my_leaky_lazy_instance;
  95. // (especially when T is MyLongTypeNameImplClientHolderFactory).
  96. // Only use this internal::-qualified verbose form to extend this traits class
  97. // (depending on its implementation details).
  98. template <typename Type>
  99. struct LeakyLazyInstanceTraits {
  100. static const bool kRegisterOnExit = false;
  101. #if DCHECK_IS_ON()
  102. static const bool kAllowedToAccessOnNonjoinableThread = true;
  103. #endif
  104. static Type* New(void* instance) {
  105. ANNOTATE_SCOPED_MEMORY_LEAK;
  106. return LazyInstanceTraitsBase<Type>::New(instance);
  107. }
  108. static void Delete(Type* instance) {
  109. }
  110. };
  111. template <typename Type>
  112. struct ErrorMustSelectLazyOrDestructorAtExitForLazyInstance {};
  113. } // namespace internal
  114. template <
  115. typename Type,
  116. typename Traits =
  117. internal::ErrorMustSelectLazyOrDestructorAtExitForLazyInstance<Type>>
  118. class LazyInstance {
  119. public:
  120. // Do not define a destructor, as doing so makes LazyInstance a
  121. // non-POD-struct. We don't want that because then a static initializer will
  122. // be created to register the (empty) destructor with atexit() under MSVC, for
  123. // example. We handle destruction of the contained Type class explicitly via
  124. // the OnExit member function, where needed.
  125. // ~LazyInstance() {}
  126. // Convenience typedef to avoid having to repeat Type for leaky lazy
  127. // instances.
  128. typedef LazyInstance<Type, internal::LeakyLazyInstanceTraits<Type>> Leaky;
  129. typedef LazyInstance<Type, internal::DestructorAtExitLazyInstanceTraits<Type>>
  130. DestructorAtExit;
  131. Type& Get() {
  132. return *Pointer();
  133. }
  134. Type* Pointer() {
  135. #if DCHECK_IS_ON()
  136. if (!Traits::kAllowedToAccessOnNonjoinableThread)
  137. internal::AssertSingletonAllowed();
  138. #endif
  139. return subtle::GetOrCreateLazyPointer(
  140. private_instance_, &Traits::New, private_buf_,
  141. Traits::kRegisterOnExit ? OnExit : nullptr, this);
  142. }
  143. // Returns true if the lazy instance has been created. Unlike Get() and
  144. // Pointer(), calling IsCreated() will not instantiate the object of Type.
  145. bool IsCreated() {
  146. // Return true (i.e. "created") if |private_instance_| is either being
  147. // created right now (i.e. |private_instance_| has value of
  148. // internal::kLazyInstanceStateCreating) or was already created (i.e.
  149. // |private_instance_| has any other non-zero value).
  150. return 0 != private_instance_.load(std::memory_order_relaxed);
  151. }
  152. // MSVC gives a warning that the alignment expands the size of the
  153. // LazyInstance struct to make the size a multiple of the alignment. This
  154. // is expected in this case.
  155. #if BUILDFLAG(IS_WIN)
  156. #pragma warning(push)
  157. #pragma warning(disable : 4324)
  158. #endif
  159. // Effectively private: member data is only public to allow the linker to
  160. // statically initialize it and to maintain a POD class. DO NOT USE FROM
  161. // OUTSIDE THIS CLASS.
  162. std::atomic<uintptr_t> private_instance_;
  163. // Preallocated space for the Type instance.
  164. alignas(Type) char private_buf_[sizeof(Type)];
  165. #if BUILDFLAG(IS_WIN)
  166. #pragma warning(pop)
  167. #endif
  168. private:
  169. Type* instance() {
  170. return reinterpret_cast<Type*>(
  171. private_instance_.load(std::memory_order_relaxed));
  172. }
  173. // Adapter function for use with AtExit. This should be called single
  174. // threaded, so don't synchronize across threads.
  175. // Calling OnExit while the instance is in use by other threads is a mistake.
  176. static void OnExit(void* lazy_instance) {
  177. LazyInstance<Type, Traits>* me =
  178. reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance);
  179. Traits::Delete(me->instance());
  180. me->private_instance_.store(0, std::memory_order_relaxed);
  181. }
  182. };
  183. } // namespace base
  184. #endif // BASE_LAZY_INSTANCE_H_