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