weak_ptr.h 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /*
  2. * Copyright 2016 The WebRTC Project Authors. All rights reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef RTC_BASE_WEAK_PTR_H_
  11. #define RTC_BASE_WEAK_PTR_H_
  12. #include <memory>
  13. #include <utility>
  14. #include "api/scoped_refptr.h"
  15. #include "rtc_base/ref_count.h"
  16. #include "rtc_base/ref_counted_object.h"
  17. #include "rtc_base/synchronization/sequence_checker.h"
  18. // The implementation is borrowed from chromium except that it does not
  19. // implement SupportsWeakPtr.
  20. // Weak pointers are pointers to an object that do not affect its lifetime,
  21. // and which may be invalidated (i.e. reset to nullptr) by the object, or its
  22. // owner, at any time, most commonly when the object is about to be deleted.
  23. // Weak pointers are useful when an object needs to be accessed safely by one
  24. // or more objects other than its owner, and those callers can cope with the
  25. // object vanishing and e.g. tasks posted to it being silently dropped.
  26. // Reference-counting such an object would complicate the ownership graph and
  27. // make it harder to reason about the object's lifetime.
  28. // EXAMPLE:
  29. //
  30. // class Controller {
  31. // public:
  32. // Controller() : weak_factory_(this) {}
  33. // void SpawnWorker() { Worker::StartNew(weak_factory_.GetWeakPtr()); }
  34. // void WorkComplete(const Result& result) { ... }
  35. // private:
  36. // // Member variables should appear before the WeakPtrFactory, to ensure
  37. // // that any WeakPtrs to Controller are invalidated before its members
  38. // // variable's destructors are executed, rendering them invalid.
  39. // WeakPtrFactory<Controller> weak_factory_;
  40. // };
  41. //
  42. // class Worker {
  43. // public:
  44. // static void StartNew(const WeakPtr<Controller>& controller) {
  45. // Worker* worker = new Worker(controller);
  46. // // Kick off asynchronous processing...
  47. // }
  48. // private:
  49. // Worker(const WeakPtr<Controller>& controller)
  50. // : controller_(controller) {}
  51. // void DidCompleteAsynchronousProcessing(const Result& result) {
  52. // if (controller_)
  53. // controller_->WorkComplete(result);
  54. // }
  55. // WeakPtr<Controller> controller_;
  56. // };
  57. //
  58. // With this implementation a caller may use SpawnWorker() to dispatch multiple
  59. // Workers and subsequently delete the Controller, without waiting for all
  60. // Workers to have completed.
  61. // ------------------------- IMPORTANT: Thread-safety -------------------------
  62. // Weak pointers may be passed safely between threads, but must always be
  63. // dereferenced and invalidated on the same TaskQueue or thread, otherwise
  64. // checking the pointer would be racey.
  65. //
  66. // To ensure correct use, the first time a WeakPtr issued by a WeakPtrFactory
  67. // is dereferenced, the factory and its WeakPtrs become bound to the calling
  68. // TaskQueue/thread, and cannot be dereferenced or
  69. // invalidated on any other TaskQueue/thread. Bound WeakPtrs can still be handed
  70. // off to other TaskQueues, e.g. to use to post tasks back to object on the
  71. // bound sequence.
  72. //
  73. // Thus, at least one WeakPtr object must exist and have been dereferenced on
  74. // the correct thread to enforce that other WeakPtr objects will enforce they
  75. // are used on the desired thread.
  76. namespace rtc {
  77. namespace internal {
  78. class WeakReference {
  79. public:
  80. // Although Flag is bound to a specific sequence, it may be
  81. // deleted from another via base::WeakPtr::~WeakPtr().
  82. class Flag : public RefCountInterface {
  83. public:
  84. Flag();
  85. void Invalidate();
  86. bool IsValid() const;
  87. private:
  88. friend class RefCountedObject<Flag>;
  89. ~Flag() override;
  90. ::webrtc::SequenceChecker checker_;
  91. bool is_valid_;
  92. };
  93. WeakReference();
  94. explicit WeakReference(const Flag* flag);
  95. ~WeakReference();
  96. WeakReference(WeakReference&& other);
  97. WeakReference(const WeakReference& other);
  98. WeakReference& operator=(WeakReference&& other) = default;
  99. WeakReference& operator=(const WeakReference& other) = default;
  100. bool is_valid() const;
  101. private:
  102. scoped_refptr<const Flag> flag_;
  103. };
  104. class WeakReferenceOwner {
  105. public:
  106. WeakReferenceOwner();
  107. ~WeakReferenceOwner();
  108. WeakReference GetRef() const;
  109. bool HasRefs() const { return flag_.get() && !flag_->HasOneRef(); }
  110. void Invalidate();
  111. private:
  112. mutable scoped_refptr<RefCountedObject<WeakReference::Flag>> flag_;
  113. };
  114. // This class simplifies the implementation of WeakPtr's type conversion
  115. // constructor by avoiding the need for a public accessor for ref_. A
  116. // WeakPtr<T> cannot access the private members of WeakPtr<U>, so this
  117. // base class gives us a way to access ref_ in a protected fashion.
  118. class WeakPtrBase {
  119. public:
  120. WeakPtrBase();
  121. ~WeakPtrBase();
  122. WeakPtrBase(const WeakPtrBase& other) = default;
  123. WeakPtrBase(WeakPtrBase&& other) = default;
  124. WeakPtrBase& operator=(const WeakPtrBase& other) = default;
  125. WeakPtrBase& operator=(WeakPtrBase&& other) = default;
  126. protected:
  127. explicit WeakPtrBase(const WeakReference& ref);
  128. WeakReference ref_;
  129. };
  130. } // namespace internal
  131. template <typename T>
  132. class WeakPtrFactory;
  133. template <typename T>
  134. class WeakPtr : public internal::WeakPtrBase {
  135. public:
  136. WeakPtr() : ptr_(nullptr) {}
  137. // Allow conversion from U to T provided U "is a" T. Note that this
  138. // is separate from the (implicit) copy and move constructors.
  139. template <typename U>
  140. WeakPtr(const WeakPtr<U>& other)
  141. : internal::WeakPtrBase(other), ptr_(other.ptr_) {}
  142. template <typename U>
  143. WeakPtr(WeakPtr<U>&& other)
  144. : internal::WeakPtrBase(std::move(other)), ptr_(other.ptr_) {}
  145. T* get() const { return ref_.is_valid() ? ptr_ : nullptr; }
  146. T& operator*() const {
  147. RTC_DCHECK(get() != nullptr);
  148. return *get();
  149. }
  150. T* operator->() const {
  151. RTC_DCHECK(get() != nullptr);
  152. return get();
  153. }
  154. void reset() {
  155. ref_ = internal::WeakReference();
  156. ptr_ = nullptr;
  157. }
  158. // Allow conditionals to test validity, e.g. if (weak_ptr) {...};
  159. explicit operator bool() const { return get() != nullptr; }
  160. private:
  161. template <typename U>
  162. friend class WeakPtr;
  163. friend class WeakPtrFactory<T>;
  164. WeakPtr(const internal::WeakReference& ref, T* ptr)
  165. : internal::WeakPtrBase(ref), ptr_(ptr) {}
  166. // This pointer is only valid when ref_.is_valid() is true. Otherwise, its
  167. // value is undefined (as opposed to nullptr).
  168. T* ptr_;
  169. };
  170. // Allow callers to compare WeakPtrs against nullptr to test validity.
  171. template <class T>
  172. bool operator!=(const WeakPtr<T>& weak_ptr, std::nullptr_t) {
  173. return !(weak_ptr == nullptr);
  174. }
  175. template <class T>
  176. bool operator!=(std::nullptr_t, const WeakPtr<T>& weak_ptr) {
  177. return weak_ptr != nullptr;
  178. }
  179. template <class T>
  180. bool operator==(const WeakPtr<T>& weak_ptr, std::nullptr_t) {
  181. return weak_ptr.get() == nullptr;
  182. }
  183. template <class T>
  184. bool operator==(std::nullptr_t, const WeakPtr<T>& weak_ptr) {
  185. return weak_ptr == nullptr;
  186. }
  187. // A class may be composed of a WeakPtrFactory and thereby
  188. // control how it exposes weak pointers to itself. This is helpful if you only
  189. // need weak pointers within the implementation of a class. This class is also
  190. // useful when working with primitive types. For example, you could have a
  191. // WeakPtrFactory<bool> that is used to pass around a weak reference to a bool.
  192. // Note that GetWeakPtr must be called on one and only one TaskQueue or thread
  193. // and the WeakPtr must only be dereferenced and invalidated on that same
  194. // TaskQueue/thread. A WeakPtr instance can be copied and posted to other
  195. // sequences though as long as it is not dereferenced (WeakPtr<T>::get()).
  196. template <class T>
  197. class WeakPtrFactory {
  198. public:
  199. explicit WeakPtrFactory(T* ptr) : ptr_(ptr) {}
  200. ~WeakPtrFactory() { ptr_ = nullptr; }
  201. WeakPtr<T> GetWeakPtr() {
  202. RTC_DCHECK(ptr_);
  203. return WeakPtr<T>(weak_reference_owner_.GetRef(), ptr_);
  204. }
  205. // Call this method to invalidate all existing weak pointers.
  206. void InvalidateWeakPtrs() {
  207. RTC_DCHECK(ptr_);
  208. weak_reference_owner_.Invalidate();
  209. }
  210. // Call this method to determine if any weak pointers exist.
  211. bool HasWeakPtrs() const {
  212. RTC_DCHECK(ptr_);
  213. return weak_reference_owner_.HasRefs();
  214. }
  215. private:
  216. internal::WeakReferenceOwner weak_reference_owner_;
  217. T* ptr_;
  218. RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory);
  219. };
  220. } // namespace rtc
  221. #endif // RTC_BASE_WEAK_PTR_H_