weak_ptr.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. // Weak pointers are pointers to an object that do not affect its lifetime,
  5. // and which may be invalidated (i.e. reset to nullptr) by the object, or its
  6. // owner, at any time, most commonly when the object is about to be deleted.
  7. // Weak pointers are useful when an object needs to be accessed safely by one
  8. // or more objects other than its owner, and those callers can cope with the
  9. // object vanishing and e.g. tasks posted to it being silently dropped.
  10. // Reference-counting such an object would complicate the ownership graph and
  11. // make it harder to reason about the object's lifetime.
  12. // EXAMPLE:
  13. //
  14. // class Controller {
  15. // public:
  16. // void SpawnWorker() { Worker::StartNew(weak_factory_.GetWeakPtr()); }
  17. // void WorkComplete(const Result& result) { ... }
  18. // private:
  19. // // Member variables should appear before the WeakPtrFactory, to ensure
  20. // // that any WeakPtrs to Controller are invalidated before its members
  21. // // variable's destructors are executed, rendering them invalid.
  22. // WeakPtrFactory<Controller> weak_factory_{this};
  23. // };
  24. //
  25. // class Worker {
  26. // public:
  27. // static void StartNew(const WeakPtr<Controller>& controller) {
  28. // Worker* worker = new Worker(controller);
  29. // // Kick off asynchronous processing...
  30. // }
  31. // private:
  32. // Worker(const WeakPtr<Controller>& controller)
  33. // : controller_(controller) {}
  34. // void DidCompleteAsynchronousProcessing(const Result& result) {
  35. // if (controller_)
  36. // controller_->WorkComplete(result);
  37. // }
  38. // WeakPtr<Controller> controller_;
  39. // };
  40. //
  41. // With this implementation a caller may use SpawnWorker() to dispatch multiple
  42. // Workers and subsequently delete the Controller, without waiting for all
  43. // Workers to have completed.
  44. // ------------------------- IMPORTANT: Thread-safety -------------------------
  45. // Weak pointers may be passed safely between sequences, but must always be
  46. // dereferenced and invalidated on the same SequencedTaskRunner otherwise
  47. // checking the pointer would be racey.
  48. //
  49. // To ensure correct use, the first time a WeakPtr issued by a WeakPtrFactory
  50. // is dereferenced, the factory and its WeakPtrs become bound to the calling
  51. // sequence or current SequencedWorkerPool token, and cannot be dereferenced or
  52. // invalidated on any other task runner. Bound WeakPtrs can still be handed
  53. // off to other task runners, e.g. to use to post tasks back to object on the
  54. // bound sequence.
  55. //
  56. // If all WeakPtr objects are destroyed or invalidated then the factory is
  57. // unbound from the SequencedTaskRunner/Thread. The WeakPtrFactory may then be
  58. // destroyed, or new WeakPtr objects may be used, from a different sequence.
  59. //
  60. // Thus, at least one WeakPtr object must exist and have been dereferenced on
  61. // the correct sequence to enforce that other WeakPtr objects will enforce they
  62. // are used on the desired sequence.
  63. #ifndef BASE_MEMORY_WEAK_PTR_H_
  64. #define BASE_MEMORY_WEAK_PTR_H_
  65. #include <cstddef>
  66. #include <type_traits>
  67. #include "base/base_export.h"
  68. #include "base/check.h"
  69. #include "base/macros.h"
  70. #include "base/memory/ref_counted.h"
  71. #include "base/sequence_checker.h"
  72. #include "base/synchronization/atomic_flag.h"
  73. namespace base {
  74. template <typename T> class SupportsWeakPtr;
  75. template <typename T> class WeakPtr;
  76. namespace internal {
  77. // These classes are part of the WeakPtr implementation.
  78. // DO NOT USE THESE CLASSES DIRECTLY YOURSELF.
  79. class BASE_EXPORT WeakReference {
  80. public:
  81. // Although Flag is bound to a specific SequencedTaskRunner, it may be
  82. // deleted from another via base::WeakPtr::~WeakPtr().
  83. class BASE_EXPORT Flag : public RefCountedThreadSafe<Flag> {
  84. public:
  85. Flag();
  86. void Invalidate();
  87. bool IsValid() const;
  88. bool MaybeValid() const;
  89. void DetachFromSequence();
  90. private:
  91. friend class base::RefCountedThreadSafe<Flag>;
  92. ~Flag();
  93. SEQUENCE_CHECKER(sequence_checker_);
  94. AtomicFlag invalidated_;
  95. };
  96. WeakReference();
  97. explicit WeakReference(const scoped_refptr<Flag>& flag);
  98. ~WeakReference();
  99. WeakReference(WeakReference&& other) noexcept;
  100. WeakReference(const WeakReference& other);
  101. WeakReference& operator=(WeakReference&& other) noexcept = default;
  102. WeakReference& operator=(const WeakReference& other) = default;
  103. bool IsValid() const;
  104. bool MaybeValid() const;
  105. private:
  106. scoped_refptr<const Flag> flag_;
  107. };
  108. class BASE_EXPORT WeakReferenceOwner {
  109. public:
  110. WeakReferenceOwner();
  111. ~WeakReferenceOwner();
  112. WeakReference GetRef() const;
  113. bool HasRefs() const { return !flag_->HasOneRef(); }
  114. void Invalidate();
  115. private:
  116. scoped_refptr<WeakReference::Flag> flag_;
  117. };
  118. // This class simplifies the implementation of WeakPtr's type conversion
  119. // constructor by avoiding the need for a public accessor for ref_. A
  120. // WeakPtr<T> cannot access the private members of WeakPtr<U>, so this
  121. // base class gives us a way to access ref_ in a protected fashion.
  122. class BASE_EXPORT WeakPtrBase {
  123. public:
  124. WeakPtrBase();
  125. ~WeakPtrBase();
  126. WeakPtrBase(const WeakPtrBase& other) = default;
  127. WeakPtrBase(WeakPtrBase&& other) noexcept = default;
  128. WeakPtrBase& operator=(const WeakPtrBase& other) = default;
  129. WeakPtrBase& operator=(WeakPtrBase&& other) noexcept = default;
  130. void reset() {
  131. ref_ = internal::WeakReference();
  132. ptr_ = 0;
  133. }
  134. protected:
  135. WeakPtrBase(const WeakReference& ref, uintptr_t ptr);
  136. WeakReference ref_;
  137. // This pointer is only valid when ref_.is_valid() is true. Otherwise, its
  138. // value is undefined (as opposed to nullptr).
  139. uintptr_t ptr_;
  140. };
  141. // This class provides a common implementation of common functions that would
  142. // otherwise get instantiated separately for each distinct instantiation of
  143. // SupportsWeakPtr<>.
  144. class SupportsWeakPtrBase {
  145. public:
  146. // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This
  147. // conversion will only compile if there is exists a Base which inherits
  148. // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper
  149. // function that makes calling this easier.
  150. //
  151. // Precondition: t != nullptr
  152. template<typename Derived>
  153. static WeakPtr<Derived> StaticAsWeakPtr(Derived* t) {
  154. static_assert(
  155. std::is_base_of<internal::SupportsWeakPtrBase, Derived>::value,
  156. "AsWeakPtr argument must inherit from SupportsWeakPtr");
  157. return AsWeakPtrImpl<Derived>(t);
  158. }
  159. private:
  160. // This template function uses type inference to find a Base of Derived
  161. // which is an instance of SupportsWeakPtr<Base>. We can then safely
  162. // static_cast the Base* to a Derived*.
  163. template <typename Derived, typename Base>
  164. static WeakPtr<Derived> AsWeakPtrImpl(SupportsWeakPtr<Base>* t) {
  165. WeakPtr<Base> ptr = t->AsWeakPtr();
  166. return WeakPtr<Derived>(
  167. ptr.ref_, static_cast<Derived*>(reinterpret_cast<Base*>(ptr.ptr_)));
  168. }
  169. };
  170. } // namespace internal
  171. template <typename T> class WeakPtrFactory;
  172. // The WeakPtr class holds a weak reference to |T*|.
  173. //
  174. // This class is designed to be used like a normal pointer. You should always
  175. // null-test an object of this class before using it or invoking a method that
  176. // may result in the underlying object being destroyed.
  177. //
  178. // EXAMPLE:
  179. //
  180. // class Foo { ... };
  181. // WeakPtr<Foo> foo;
  182. // if (foo)
  183. // foo->method();
  184. //
  185. template <typename T>
  186. class WeakPtr : public internal::WeakPtrBase {
  187. public:
  188. WeakPtr() = default;
  189. WeakPtr(std::nullptr_t) {}
  190. // Allow conversion from U to T provided U "is a" T. Note that this
  191. // is separate from the (implicit) copy and move constructors.
  192. template <typename U>
  193. WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other) {
  194. // Need to cast from U* to T* to do pointer adjustment in case of multiple
  195. // inheritance. This also enforces the "U is a T" rule.
  196. T* t = reinterpret_cast<U*>(other.ptr_);
  197. ptr_ = reinterpret_cast<uintptr_t>(t);
  198. }
  199. template <typename U>
  200. WeakPtr(WeakPtr<U>&& other) noexcept : WeakPtrBase(std::move(other)) {
  201. // Need to cast from U* to T* to do pointer adjustment in case of multiple
  202. // inheritance. This also enforces the "U is a T" rule.
  203. T* t = reinterpret_cast<U*>(other.ptr_);
  204. ptr_ = reinterpret_cast<uintptr_t>(t);
  205. }
  206. T* get() const {
  207. return ref_.IsValid() ? reinterpret_cast<T*>(ptr_) : nullptr;
  208. }
  209. T& operator*() const {
  210. DCHECK(get() != nullptr);
  211. return *get();
  212. }
  213. T* operator->() const {
  214. DCHECK(get() != nullptr);
  215. return get();
  216. }
  217. // Allow conditionals to test validity, e.g. if (weak_ptr) {...};
  218. explicit operator bool() const { return get() != nullptr; }
  219. // Returns false if the WeakPtr is confirmed to be invalid. This call is safe
  220. // to make from any thread, e.g. to optimize away unnecessary work, but
  221. // operator bool() must always be called, on the correct sequence, before
  222. // actually using the pointer.
  223. //
  224. // Warning: as with any object, this call is only thread-safe if the WeakPtr
  225. // instance isn't being re-assigned or reset() racily with this call.
  226. bool MaybeValid() const { return ref_.MaybeValid(); }
  227. // Returns whether the object |this| points to has been invalidated. This can
  228. // be used to distinguish a WeakPtr to a destroyed object from one that has
  229. // been explicitly set to null.
  230. bool WasInvalidated() const { return ptr_ && !ref_.IsValid(); }
  231. private:
  232. friend class internal::SupportsWeakPtrBase;
  233. template <typename U> friend class WeakPtr;
  234. friend class SupportsWeakPtr<T>;
  235. friend class WeakPtrFactory<T>;
  236. WeakPtr(const internal::WeakReference& ref, T* ptr)
  237. : WeakPtrBase(ref, reinterpret_cast<uintptr_t>(ptr)) {}
  238. };
  239. // Allow callers to compare WeakPtrs against nullptr to test validity.
  240. template <class T>
  241. bool operator!=(const WeakPtr<T>& weak_ptr, std::nullptr_t) {
  242. return !(weak_ptr == nullptr);
  243. }
  244. template <class T>
  245. bool operator!=(std::nullptr_t, const WeakPtr<T>& weak_ptr) {
  246. return weak_ptr != nullptr;
  247. }
  248. template <class T>
  249. bool operator==(const WeakPtr<T>& weak_ptr, std::nullptr_t) {
  250. return weak_ptr.get() == nullptr;
  251. }
  252. template <class T>
  253. bool operator==(std::nullptr_t, const WeakPtr<T>& weak_ptr) {
  254. return weak_ptr == nullptr;
  255. }
  256. namespace internal {
  257. class BASE_EXPORT WeakPtrFactoryBase {
  258. protected:
  259. WeakPtrFactoryBase(uintptr_t ptr);
  260. ~WeakPtrFactoryBase();
  261. internal::WeakReferenceOwner weak_reference_owner_;
  262. uintptr_t ptr_;
  263. };
  264. } // namespace internal
  265. // A class may be composed of a WeakPtrFactory and thereby
  266. // control how it exposes weak pointers to itself. This is helpful if you only
  267. // need weak pointers within the implementation of a class. This class is also
  268. // useful when working with primitive types. For example, you could have a
  269. // WeakPtrFactory<bool> that is used to pass around a weak reference to a bool.
  270. template <class T>
  271. class WeakPtrFactory : public internal::WeakPtrFactoryBase {
  272. public:
  273. explicit WeakPtrFactory(T* ptr)
  274. : WeakPtrFactoryBase(reinterpret_cast<uintptr_t>(ptr)) {}
  275. ~WeakPtrFactory() = default;
  276. WeakPtr<T> GetWeakPtr() const {
  277. return WeakPtr<T>(weak_reference_owner_.GetRef(),
  278. reinterpret_cast<T*>(ptr_));
  279. }
  280. // Call this method to invalidate all existing weak pointers.
  281. void InvalidateWeakPtrs() {
  282. DCHECK(ptr_);
  283. weak_reference_owner_.Invalidate();
  284. }
  285. // Call this method to determine if any weak pointers exist.
  286. bool HasWeakPtrs() const {
  287. DCHECK(ptr_);
  288. return weak_reference_owner_.HasRefs();
  289. }
  290. private:
  291. DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory);
  292. };
  293. // A class may extend from SupportsWeakPtr to let others take weak pointers to
  294. // it. This avoids the class itself implementing boilerplate to dispense weak
  295. // pointers. However, since SupportsWeakPtr's destructor won't invalidate
  296. // weak pointers to the class until after the derived class' members have been
  297. // destroyed, its use can lead to subtle use-after-destroy issues.
  298. template <class T>
  299. class SupportsWeakPtr : public internal::SupportsWeakPtrBase {
  300. public:
  301. SupportsWeakPtr() = default;
  302. WeakPtr<T> AsWeakPtr() {
  303. return WeakPtr<T>(weak_reference_owner_.GetRef(), static_cast<T*>(this));
  304. }
  305. protected:
  306. ~SupportsWeakPtr() = default;
  307. private:
  308. internal::WeakReferenceOwner weak_reference_owner_;
  309. DISALLOW_COPY_AND_ASSIGN(SupportsWeakPtr);
  310. };
  311. // Helper function that uses type deduction to safely return a WeakPtr<Derived>
  312. // when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it
  313. // extends a Base that extends SupportsWeakPtr<Base>.
  314. //
  315. // EXAMPLE:
  316. // class Base : public base::SupportsWeakPtr<Producer> {};
  317. // class Derived : public Base {};
  318. //
  319. // Derived derived;
  320. // base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived);
  321. //
  322. // Note that the following doesn't work (invalid type conversion) since
  323. // Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(),
  324. // and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at
  325. // the caller.
  326. //
  327. // base::WeakPtr<Derived> ptr = derived.AsWeakPtr(); // Fails.
  328. template <typename Derived>
  329. WeakPtr<Derived> AsWeakPtr(Derived* t) {
  330. return internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t);
  331. }
  332. } // namespace base
  333. #endif // BASE_MEMORY_WEAK_PTR_H_