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/memory/ref_counted.h"
78
79 namespace base {
80
81 template <typename T>
82 class SupportsWeakPtr;
83 template <typename T>
84 class WeakPtr;
85
86 namespace internal {
87 // These classes are part of the WeakPtr implementation.
88 // DO NOT USE THESE CLASSES DIRECTLY YOURSELF.
89
90 class WeakReference {
91 public:
92 // Although Flag is bound to a specific SequencedTaskRunner, it may be
93 // deleted from another via base::WeakPtr::~WeakPtr().
94 class Flag : public RefCountedThreadSafe<Flag> {
95 public:
96 Flag();
97
98 void Invalidate();
99 bool IsValid() const;
100
101 private:
102 friend class base::RefCountedThreadSafe<Flag>;
103
104 ~Flag();
105
106 bool is_valid_;
107 };
108
109 WeakReference();
110 explicit WeakReference(const scoped_refptr<Flag>& flag);
111 ~WeakReference();
112
113 WeakReference(WeakReference&& other);
114 WeakReference(const WeakReference& other);
115 WeakReference& operator=(WeakReference&& other) = default;
116 WeakReference& operator=(const WeakReference& other) = default;
117
118 bool is_valid() const;
119
120 private:
121 scoped_refptr<const Flag> flag_;
122 };
123
124 class WeakReferenceOwner {
125 public:
126 WeakReferenceOwner();
127 ~WeakReferenceOwner();
128
129 WeakReference GetRef() const;
130
HasRefs()131 bool HasRefs() const { return flag_ && !flag_->HasOneRef(); }
132
133 void Invalidate();
134
135 private:
136 mutable scoped_refptr<WeakReference::Flag> flag_;
137 };
138
139 // This class simplifies the implementation of WeakPtr's type conversion
140 // constructor by avoiding the need for a public accessor for ref_. A
141 // WeakPtr<T> cannot access the private members of WeakPtr<U>, so this
142 // base class gives us a way to access ref_ in a protected fashion.
143 class WeakPtrBase {
144 public:
145 WeakPtrBase();
146 ~WeakPtrBase();
147
148 WeakPtrBase(const WeakPtrBase& other) = default;
149 WeakPtrBase(WeakPtrBase&& other) = default;
150 WeakPtrBase& operator=(const WeakPtrBase& other) = default;
151 WeakPtrBase& operator=(WeakPtrBase&& other) = default;
152
reset()153 void reset() {
154 ref_ = internal::WeakReference();
155 ptr_ = 0;
156 }
157
158 protected:
159 WeakPtrBase(const WeakReference& ref, uintptr_t ptr);
160
161 WeakReference ref_;
162
163 // This pointer is only valid when ref_.is_valid() is true. Otherwise, its
164 // value is undefined (as opposed to nullptr).
165 uintptr_t ptr_;
166 };
167
168 // This class provides a common implementation of common functions that would
169 // otherwise get instantiated separately for each distinct instantiation of
170 // SupportsWeakPtr<>.
171 class SupportsWeakPtrBase {
172 public:
173 // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This
174 // conversion will only compile if there is exists a Base which inherits
175 // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper
176 // function that makes calling this easier.
177 //
178 // Precondition: t != nullptr
179 template <typename Derived>
StaticAsWeakPtr(Derived * t)180 static WeakPtr<Derived> StaticAsWeakPtr(Derived* t) {
181 static_assert(
182 std::is_base_of<internal::SupportsWeakPtrBase, Derived>::value,
183 "AsWeakPtr argument must inherit from SupportsWeakPtr");
184 return AsWeakPtrImpl<Derived>(t);
185 }
186
187 private:
188 // This template function uses type inference to find a Base of Derived
189 // which is an instance of SupportsWeakPtr<Base>. We can then safely
190 // static_cast the Base* to a Derived*.
191 template <typename Derived, typename Base>
AsWeakPtrImpl(SupportsWeakPtr<Base> * t)192 static WeakPtr<Derived> AsWeakPtrImpl(SupportsWeakPtr<Base>* t) {
193 WeakPtr<Base> ptr = t->AsWeakPtr();
194 return WeakPtr<Derived>(
195 ptr.ref_, static_cast<Derived*>(reinterpret_cast<Base*>(ptr.ptr_)));
196 }
197 };
198
199 } // namespace internal
200
201 template <typename T>
202 class WeakPtrFactory;
203
204 // The WeakPtr class holds a weak reference to |T*|.
205 //
206 // This class is designed to be used like a normal pointer. You should always
207 // null-test an object of this class before using it or invoking a method that
208 // may result in the underlying object being destroyed.
209 //
210 // EXAMPLE:
211 //
212 // class Foo { ... };
213 // WeakPtr<Foo> foo;
214 // if (foo)
215 // foo->method();
216 //
217 template <typename T>
218 class WeakPtr : public internal::WeakPtrBase {
219 public:
220 WeakPtr() = default;
221
WeakPtr(std::nullptr_t)222 WeakPtr(std::nullptr_t) {}
223
224 // Allow conversion from U to T provided U "is a" T. Note that this
225 // is separate from the (implicit) copy and move constructors.
226 template <typename U>
WeakPtr(const WeakPtr<U> & other)227 WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other) {
228 // Need to cast from U* to T* to do pointer adjustment in case of multiple
229 // inheritance. This also enforces the "U is a T" rule.
230 T* t = reinterpret_cast<U*>(other.ptr_);
231 ptr_ = reinterpret_cast<uintptr_t>(t);
232 }
233 template <typename U>
WeakPtr(WeakPtr<U> && other)234 WeakPtr(WeakPtr<U>&& other) : WeakPtrBase(std::move(other)) {
235 // Need to cast from U* to T* to do pointer adjustment in case of multiple
236 // inheritance. This also enforces the "U is a T" rule.
237 T* t = reinterpret_cast<U*>(other.ptr_);
238 ptr_ = reinterpret_cast<uintptr_t>(t);
239 }
240
get()241 T* get() const {
242 return ref_.is_valid() ? reinterpret_cast<T*>(ptr_) : nullptr;
243 }
244
245 T& operator*() const {
246 DCHECK(get() != nullptr);
247 return *get();
248 }
249 T* operator->() const {
250 DCHECK(get() != nullptr);
251 return get();
252 }
253
254 // Allow conditionals to test validity, e.g. if (weak_ptr) {...};
255 explicit operator bool() const { return get() != nullptr; }
256
257 private:
258 friend class internal::SupportsWeakPtrBase;
259 template <typename U>
260 friend class WeakPtr;
261 friend class SupportsWeakPtr<T>;
262 friend class WeakPtrFactory<T>;
263
WeakPtr(const internal::WeakReference & ref,T * ptr)264 WeakPtr(const internal::WeakReference& ref, T* ptr)
265 : WeakPtrBase(ref, reinterpret_cast<uintptr_t>(ptr)) {}
266 };
267
268 // Allow callers to compare WeakPtrs against nullptr to test validity.
269 template <class T>
270 bool operator!=(const WeakPtr<T>& weak_ptr, std::nullptr_t) {
271 return !(weak_ptr == nullptr);
272 }
273 template <class T>
274 bool operator!=(std::nullptr_t, const WeakPtr<T>& weak_ptr) {
275 return weak_ptr != nullptr;
276 }
277 template <class T>
278 bool operator==(const WeakPtr<T>& weak_ptr, std::nullptr_t) {
279 return weak_ptr.get() == nullptr;
280 }
281 template <class T>
282 bool operator==(std::nullptr_t, const WeakPtr<T>& weak_ptr) {
283 return weak_ptr == nullptr;
284 }
285
286 namespace internal {
287 class WeakPtrFactoryBase {
288 protected:
289 WeakPtrFactoryBase(uintptr_t ptr);
290 ~WeakPtrFactoryBase();
291 internal::WeakReferenceOwner weak_reference_owner_;
292 uintptr_t ptr_;
293 };
294 } // namespace internal
295
296 // A class may be composed of a WeakPtrFactory and thereby
297 // control how it exposes weak pointers to itself. This is helpful if you only
298 // need weak pointers within the implementation of a class. This class is also
299 // useful when working with primitive types. For example, you could have a
300 // WeakPtrFactory<bool> that is used to pass around a weak reference to a bool.
301 template <class T>
302 class WeakPtrFactory : public internal::WeakPtrFactoryBase {
303 public:
WeakPtrFactory(T * ptr)304 explicit WeakPtrFactory(T* ptr)
305 : WeakPtrFactoryBase(reinterpret_cast<uintptr_t>(ptr)) {}
306
307 ~WeakPtrFactory() = default;
308
GetWeakPtr()309 WeakPtr<T> GetWeakPtr() {
310 return WeakPtr<T>(weak_reference_owner_.GetRef(),
311 reinterpret_cast<T*>(ptr_));
312 }
313
314 // Call this method to invalidate all existing weak pointers.
InvalidateWeakPtrs()315 void InvalidateWeakPtrs() {
316 DCHECK(ptr_);
317 weak_reference_owner_.Invalidate();
318 }
319
320 // Call this method to determine if any weak pointers exist.
HasWeakPtrs()321 bool HasWeakPtrs() const {
322 DCHECK(ptr_);
323 return weak_reference_owner_.HasRefs();
324 }
325
326 private:
327 WeakPtrFactory() = delete;
328 WeakPtrFactory(const WeakPtrFactory&) = delete;
329 WeakPtrFactory& operator=(const WeakPtrFactory&) = delete;
330 };
331
332 // A class may extend from SupportsWeakPtr to let others take weak pointers to
333 // it. This avoids the class itself implementing boilerplate to dispense weak
334 // pointers. However, since SupportsWeakPtr's destructor won't invalidate
335 // weak pointers to the class until after the derived class' members have been
336 // destroyed, its use can lead to subtle use-after-destroy issues.
337 template <class T>
338 class SupportsWeakPtr : public internal::SupportsWeakPtrBase {
339 public:
340 SupportsWeakPtr() = default;
341
AsWeakPtr()342 WeakPtr<T> AsWeakPtr() {
343 return WeakPtr<T>(weak_reference_owner_.GetRef(), static_cast<T*>(this));
344 }
345
346 protected:
347 ~SupportsWeakPtr() = default;
348
349 private:
350 internal::WeakReferenceOwner weak_reference_owner_;
351 SupportsWeakPtr(const SupportsWeakPtr&) = delete;
352 SupportsWeakPtr& operator=(const SupportsWeakPtr&) = delete;
353 };
354
355 // Helper function that uses type deduction to safely return a WeakPtr<Derived>
356 // when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it
357 // extends a Base that extends SupportsWeakPtr<Base>.
358 //
359 // EXAMPLE:
360 // class Base : public base::SupportsWeakPtr<Producer> {};
361 // class Derived : public Base {};
362 //
363 // Derived derived;
364 // base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived);
365 //
366 // Note that the following doesn't work (invalid type conversion) since
367 // Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(),
368 // and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at
369 // the caller.
370 //
371 // base::WeakPtr<Derived> ptr = derived.AsWeakPtr(); // Fails.
372
373 template <typename Derived>
AsWeakPtr(Derived * t)374 WeakPtr<Derived> AsWeakPtr(Derived* t) {
375 return internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t);
376 }
377
378 } // namespace base
379
380 #endif // BASE_MEMORY_WEAK_PTR_H_
381