weak_ptr.h 15 KB

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