weak_ptr.h 8.7 KB

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