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