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/logging.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   WeakReferenceOwner(WeakReferenceOwner&& other) noexcept = default;
136   WeakReferenceOwner(const WeakReferenceOwner& other) = default;
137   WeakReferenceOwner& operator=(WeakReferenceOwner&& other) noexcept = default;
138   WeakReferenceOwner& operator=(const WeakReferenceOwner& other) = default;
139 
140   WeakReference GetRef() const;
141 
HasRefs()142   bool HasRefs() const { return !flag_->HasOneRef(); }
143 
144   void Invalidate();
145 
146  private:
147   scoped_refptr<WeakReference::Flag> flag_;
148 };
149 
150 // This class simplifies the implementation of WeakPtr's type conversion
151 // constructor by avoiding the need for a public accessor for ref_.  A
152 // WeakPtr<T> cannot access the private members of WeakPtr<U>, so this
153 // base class gives us a way to access ref_ in a protected fashion.
154 class BASE_EXPORT WeakPtrBase {
155  public:
156   WeakPtrBase();
157   ~WeakPtrBase();
158 
159   WeakPtrBase(const WeakPtrBase& other) = default;
160   WeakPtrBase(WeakPtrBase&& other) noexcept = default;
161   WeakPtrBase& operator=(const WeakPtrBase& other) = default;
162   WeakPtrBase& operator=(WeakPtrBase&& other) noexcept = default;
163 
reset()164   void reset() {
165     ref_ = internal::WeakReference();
166     ptr_ = 0;
167   }
168 
169  protected:
170   WeakPtrBase(const WeakReference& ref, uintptr_t ptr);
171 
172   WeakReference ref_;
173 
174   // This pointer is only valid when ref_.is_valid() is true.  Otherwise, its
175   // value is undefined (as opposed to nullptr).
176   uintptr_t ptr_;
177 };
178 
179 // This class provides a common implementation of common functions that would
180 // otherwise get instantiated separately for each distinct instantiation of
181 // SupportsWeakPtr<>.
182 class SupportsWeakPtrBase {
183  public:
184   // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This
185   // conversion will only compile if there is exists a Base which inherits
186   // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper
187   // function that makes calling this easier.
188   //
189   // Precondition: t != nullptr
190   template<typename Derived>
StaticAsWeakPtr(Derived * t)191   static WeakPtr<Derived> StaticAsWeakPtr(Derived* t) {
192     static_assert(
193         std::is_base_of<internal::SupportsWeakPtrBase, Derived>::value,
194         "AsWeakPtr argument must inherit from SupportsWeakPtr");
195     return AsWeakPtrImpl<Derived>(t);
196   }
197 
198  private:
199   // This template function uses type inference to find a Base of Derived
200   // which is an instance of SupportsWeakPtr<Base>. We can then safely
201   // static_cast the Base* to a Derived*.
202   template <typename Derived, typename Base>
AsWeakPtrImpl(SupportsWeakPtr<Base> * t)203   static WeakPtr<Derived> AsWeakPtrImpl(SupportsWeakPtr<Base>* t) {
204     WeakPtr<Base> ptr = t->AsWeakPtr();
205     return WeakPtr<Derived>(
206         ptr.ref_, static_cast<Derived*>(reinterpret_cast<Base*>(ptr.ptr_)));
207   }
208 };
209 
210 }  // namespace internal
211 
212 template <typename T> class WeakPtrFactory;
213 
214 // The WeakPtr class holds a weak reference to |T*|.
215 //
216 // This class is designed to be used like a normal pointer.  You should always
217 // null-test an object of this class before using it or invoking a method that
218 // may result in the underlying object being destroyed.
219 //
220 // EXAMPLE:
221 //
222 //   class Foo { ... };
223 //   WeakPtr<Foo> foo;
224 //   if (foo)
225 //     foo->method();
226 //
227 template <typename T>
228 class WeakPtr : public internal::WeakPtrBase {
229  public:
230   WeakPtr() = default;
WeakPtr(std::nullptr_t)231   WeakPtr(std::nullptr_t) {}
232 
233   // Allow conversion from U to T provided U "is a" T. Note that this
234   // is separate from the (implicit) copy and move constructors.
235   template <typename U>
WeakPtr(const WeakPtr<U> & other)236   WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other) {
237     // Need to cast from U* to T* to do pointer adjustment in case of multiple
238     // inheritance. This also enforces the "U is a T" rule.
239     T* t = reinterpret_cast<U*>(other.ptr_);
240     ptr_ = reinterpret_cast<uintptr_t>(t);
241   }
242   template <typename U>
WeakPtr(WeakPtr<U> && other)243   WeakPtr(WeakPtr<U>&& other) noexcept : WeakPtrBase(std::move(other)) {
244     // Need to cast from U* to T* to do pointer adjustment in case of multiple
245     // inheritance. This also enforces the "U is a T" rule.
246     T* t = reinterpret_cast<U*>(other.ptr_);
247     ptr_ = reinterpret_cast<uintptr_t>(t);
248   }
249 
get()250   T* get() const {
251     return ref_.IsValid() ? reinterpret_cast<T*>(ptr_) : nullptr;
252   }
253 
254   T& operator*() const {
255     DCHECK(get() != nullptr);
256     return *get();
257   }
258   T* operator->() const {
259     DCHECK(get() != nullptr);
260     return get();
261   }
262 
263   // Allow conditionals to test validity, e.g. if (weak_ptr) {...};
264   explicit operator bool() const { return get() != nullptr; }
265 
266   // Returns false if the WeakPtr is confirmed to be invalid. This call is safe
267   // to make from any thread, e.g. to optimize away unnecessary work, but
268   // operator bool() must always be called, on the correct sequence, before
269   // actually using the pointer.
270   //
271   // Warning: as with any object, this call is only thread-safe if the WeakPtr
272   // instance isn't being re-assigned or reset() racily with this call.
MaybeValid()273   bool MaybeValid() const { return ref_.MaybeValid(); }
274 
275   // Returns whether the object |this| points to has been invalidated. This can
276   // be used to distinguish a WeakPtr to a destroyed object from one that has
277   // been explicitly set to null.
WasInvalidated()278   bool WasInvalidated() const { return ptr_ && !ref_.IsValid(); }
279 
280  private:
281   friend class internal::SupportsWeakPtrBase;
282   template <typename U> friend class WeakPtr;
283   friend class SupportsWeakPtr<T>;
284   friend class WeakPtrFactory<T>;
285 
WeakPtr(const internal::WeakReference & ref,T * ptr)286   WeakPtr(const internal::WeakReference& ref, T* ptr)
287       : WeakPtrBase(ref, reinterpret_cast<uintptr_t>(ptr)) {}
288 };
289 
290 // Allow callers to compare WeakPtrs against nullptr to test validity.
291 template <class T>
292 bool operator!=(const WeakPtr<T>& weak_ptr, std::nullptr_t) {
293   return !(weak_ptr == nullptr);
294 }
295 template <class T>
296 bool operator!=(std::nullptr_t, const WeakPtr<T>& weak_ptr) {
297   return weak_ptr != nullptr;
298 }
299 template <class T>
300 bool operator==(const WeakPtr<T>& weak_ptr, std::nullptr_t) {
301   return weak_ptr.get() == nullptr;
302 }
303 template <class T>
304 bool operator==(std::nullptr_t, const WeakPtr<T>& weak_ptr) {
305   return weak_ptr == nullptr;
306 }
307 
308 namespace internal {
309 class BASE_EXPORT WeakPtrFactoryBase {
310  protected:
311   WeakPtrFactoryBase(uintptr_t ptr);
312   ~WeakPtrFactoryBase();
313   internal::WeakReferenceOwner weak_reference_owner_;
314   uintptr_t ptr_;
315 };
316 }  // namespace internal
317 
318 // A class may be composed of a WeakPtrFactory and thereby
319 // control how it exposes weak pointers to itself.  This is helpful if you only
320 // need weak pointers within the implementation of a class.  This class is also
321 // useful when working with primitive types.  For example, you could have a
322 // WeakPtrFactory<bool> that is used to pass around a weak reference to a bool.
323 template <class T>
324 class WeakPtrFactory : public internal::WeakPtrFactoryBase {
325  public:
WeakPtrFactory(T * ptr)326   explicit WeakPtrFactory(T* ptr)
327       : WeakPtrFactoryBase(reinterpret_cast<uintptr_t>(ptr)) {}
328 
329   ~WeakPtrFactory() = default;
330   WeakPtrFactory(WeakPtrFactory&&) noexcept = default;
331   WeakPtrFactory& operator=(WeakPtrFactory&&) noexcept = default;
332 
GetWeakPtr()333   WeakPtr<T> GetWeakPtr() {
334     return WeakPtr<T>(weak_reference_owner_.GetRef(),
335                       reinterpret_cast<T*>(ptr_));
336   }
337 
338   // Call this method to invalidate all existing weak pointers.
InvalidateWeakPtrs()339   void InvalidateWeakPtrs() {
340     DCHECK(ptr_);
341     weak_reference_owner_.Invalidate();
342   }
343 
344   // Call this method to determine if any weak pointers exist.
HasWeakPtrs()345   bool HasWeakPtrs() const {
346     DCHECK(ptr_);
347     return weak_reference_owner_.HasRefs();
348   }
349 
350  private:
351   DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory);
352 };
353 
354 // A class may extend from SupportsWeakPtr to let others take weak pointers to
355 // it. This avoids the class itself implementing boilerplate to dispense weak
356 // pointers.  However, since SupportsWeakPtr's destructor won't invalidate
357 // weak pointers to the class until after the derived class' members have been
358 // destroyed, its use can lead to subtle use-after-destroy issues.
359 template <class T>
360 class SupportsWeakPtr : public internal::SupportsWeakPtrBase {
361  public:
362   SupportsWeakPtr() = default;
363 
AsWeakPtr()364   WeakPtr<T> AsWeakPtr() {
365     return WeakPtr<T>(weak_reference_owner_.GetRef(), static_cast<T*>(this));
366   }
367 
368  protected:
369   ~SupportsWeakPtr() = default;
370 
371  private:
372   internal::WeakReferenceOwner weak_reference_owner_;
373   DISALLOW_COPY_AND_ASSIGN(SupportsWeakPtr);
374 };
375 
376 // Helper function that uses type deduction to safely return a WeakPtr<Derived>
377 // when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it
378 // extends a Base that extends SupportsWeakPtr<Base>.
379 //
380 // EXAMPLE:
381 //   class Base : public base::SupportsWeakPtr<Producer> {};
382 //   class Derived : public Base {};
383 //
384 //   Derived derived;
385 //   base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived);
386 //
387 // Note that the following doesn't work (invalid type conversion) since
388 // Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(),
389 // and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at
390 // the caller.
391 //
392 //   base::WeakPtr<Derived> ptr = derived.AsWeakPtr();  // Fails.
393 
394 template <typename Derived>
AsWeakPtr(Derived * t)395 WeakPtr<Derived> AsWeakPtr(Derived* t) {
396   return internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t);
397 }
398 
399 }  // namespace base
400 
401 #endif  // BASE_MEMORY_WEAK_PTR_H_
402