lazy_instance.h 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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 <new> // For placement new.
  47. #include "base/atomicops.h"
  48. #include "base/check_op.h"
  49. #include "base/debug/leak_annotations.h"
  50. #include "base/lazy_instance_helpers.h"
  51. #include "base/threading/thread_restrictions.h"
  52. // LazyInstance uses its own struct initializer-list style static
  53. // initialization, which does not require a constructor.
  54. #define LAZY_INSTANCE_INITIALIZER {}
  55. namespace base {
  56. template <typename Type>
  57. struct LazyInstanceTraitsBase {
  58. static Type* New(void* instance) {
  59. DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) & (alignof(Type) - 1), 0u);
  60. // Use placement new to initialize our instance in our preallocated space.
  61. // The parenthesis is very important here to force POD type initialization.
  62. return new (instance) Type();
  63. }
  64. static void CallDestructor(Type* instance) {
  65. // Explicitly call the destructor.
  66. instance->~Type();
  67. }
  68. };
  69. // We pull out some of the functionality into non-templated functions, so we
  70. // can implement the more complicated pieces out of line in the .cc file.
  71. namespace internal {
  72. // This traits class causes destruction the contained Type at process exit via
  73. // AtExitManager. This is probably generally not what you want. Instead, prefer
  74. // Leaky below.
  75. template <typename Type>
  76. struct DestructorAtExitLazyInstanceTraits {
  77. static const bool kRegisterOnExit = true;
  78. #if DCHECK_IS_ON()
  79. static const bool kAllowedToAccessOnNonjoinableThread = false;
  80. #endif
  81. static Type* New(void* instance) {
  82. return LazyInstanceTraitsBase<Type>::New(instance);
  83. }
  84. static void Delete(Type* instance) {
  85. LazyInstanceTraitsBase<Type>::CallDestructor(instance);
  86. }
  87. };
  88. // Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.:
  89. // base::LazyInstance<T>::Leaky my_leaky_lazy_instance;
  90. // instead of:
  91. // base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> >
  92. // my_leaky_lazy_instance;
  93. // (especially when T is MyLongTypeNameImplClientHolderFactory).
  94. // Only use this internal::-qualified verbose form to extend this traits class
  95. // (depending on its implementation details).
  96. template <typename Type>
  97. struct LeakyLazyInstanceTraits {
  98. static const bool kRegisterOnExit = false;
  99. #if DCHECK_IS_ON()
  100. static const bool kAllowedToAccessOnNonjoinableThread = true;
  101. #endif
  102. static Type* New(void* instance) {
  103. ANNOTATE_SCOPED_MEMORY_LEAK;
  104. return LazyInstanceTraitsBase<Type>::New(instance);
  105. }
  106. static void Delete(Type* instance) {
  107. }
  108. };
  109. template <typename Type>
  110. struct ErrorMustSelectLazyOrDestructorAtExitForLazyInstance {};
  111. } // namespace internal
  112. template <
  113. typename Type,
  114. typename Traits =
  115. internal::ErrorMustSelectLazyOrDestructorAtExitForLazyInstance<Type>>
  116. class LazyInstance {
  117. public:
  118. // Do not define a destructor, as doing so makes LazyInstance a
  119. // non-POD-struct. We don't want that because then a static initializer will
  120. // be created to register the (empty) destructor with atexit() under MSVC, for
  121. // example. We handle destruction of the contained Type class explicitly via
  122. // the OnExit member function, where needed.
  123. // ~LazyInstance() {}
  124. // Convenience typedef to avoid having to repeat Type for leaky lazy
  125. // instances.
  126. typedef LazyInstance<Type, internal::LeakyLazyInstanceTraits<Type>> Leaky;
  127. typedef LazyInstance<Type, internal::DestructorAtExitLazyInstanceTraits<Type>>
  128. DestructorAtExit;
  129. Type& Get() {
  130. return *Pointer();
  131. }
  132. Type* Pointer() {
  133. #if DCHECK_IS_ON()
  134. if (!Traits::kAllowedToAccessOnNonjoinableThread)
  135. ThreadRestrictions::AssertSingletonAllowed();
  136. #endif
  137. return subtle::GetOrCreateLazyPointer(
  138. &private_instance_, &Traits::New, private_buf_,
  139. Traits::kRegisterOnExit ? OnExit : nullptr, this);
  140. }
  141. // Returns true if the lazy instance has been created. Unlike Get() and
  142. // Pointer(), calling IsCreated() will not instantiate the object of Type.
  143. bool IsCreated() {
  144. // Return true (i.e. "created") if |private_instance_| is either being
  145. // created right now (i.e. |private_instance_| has value of
  146. // internal::kLazyInstanceStateCreating) or was already created (i.e.
  147. // |private_instance_| has any other non-zero value).
  148. return 0 != subtle::NoBarrier_Load(&private_instance_);
  149. }
  150. // MSVC gives a warning that the alignment expands the size of the
  151. // LazyInstance struct to make the size a multiple of the alignment. This
  152. // is expected in this case.
  153. #if defined(OS_WIN)
  154. #pragma warning(push)
  155. #pragma warning(disable: 4324)
  156. #endif
  157. // Effectively private: member data is only public to allow the linker to
  158. // statically initialize it and to maintain a POD class. DO NOT USE FROM
  159. // OUTSIDE THIS CLASS.
  160. subtle::AtomicWord private_instance_;
  161. // Preallocated space for the Type instance.
  162. alignas(Type) char private_buf_[sizeof(Type)];
  163. #if defined(OS_WIN)
  164. #pragma warning(pop)
  165. #endif
  166. private:
  167. Type* instance() {
  168. return reinterpret_cast<Type*>(subtle::NoBarrier_Load(&private_instance_));
  169. }
  170. // Adapter function for use with AtExit. This should be called single
  171. // threaded, so don't synchronize across threads.
  172. // Calling OnExit while the instance is in use by other threads is a mistake.
  173. static void OnExit(void* lazy_instance) {
  174. LazyInstance<Type, Traits>* me =
  175. reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance);
  176. Traits::Delete(me->instance());
  177. subtle::NoBarrier_Store(&me->private_instance_, 0);
  178. }
  179. };
  180. } // namespace base
  181. #endif // BASE_LAZY_INSTANCE_H_