blob: e07beebeb6647adf55ef8a2a02b101ec51551eb1 [file] [log] [blame]
Vitaly Bukacbed2062015-08-17 12:54:05 -07001// 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 NULL) 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_;
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 threads, 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// thread 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// Invalidating the factory's WeakPtrs un-binds it from the sequence, allowing
62// it to be passed for a different sequence to use or delete it.
63
64#ifndef BASE_MEMORY_WEAK_PTR_H_
65#define BASE_MEMORY_WEAK_PTR_H_
66
67#include "base/basictypes.h"
68#include "base/base_export.h"
69#include "base/logging.h"
70#include "base/memory/ref_counted.h"
Vitaly Bukacbed2062015-08-17 12:54:05 -070071
72namespace base {
73
74template <typename T> class SupportsWeakPtr;
75template <typename T> class WeakPtr;
76
77namespace internal {
78// These classes are part of the WeakPtr implementation.
79// DO NOT USE THESE CLASSES DIRECTLY YOURSELF.
80
Vitaly Bukaf2f26402015-08-25 13:03:27 -070081class BASE_EXPORT WeakReference {
Vitaly Bukacbed2062015-08-17 12:54:05 -070082 public:
83 // Although Flag is bound to a specific SequencedTaskRunner, it may be
84 // deleted from another via base::WeakPtr::~WeakPtr().
Vitaly Buka60b8f002015-08-20 13:47:48 -070085 class Flag : public RefCountedThreadSafe<Flag> {
Vitaly Bukacbed2062015-08-17 12:54:05 -070086 public:
87 Flag();
88
89 void Invalidate();
90 bool IsValid() const;
91
92 private:
93 friend class base::RefCountedThreadSafe<Flag>;
94
95 ~Flag();
96
Vitaly Bukacbed2062015-08-17 12:54:05 -070097 bool is_valid_;
98 };
99
100 WeakReference();
101 explicit WeakReference(const Flag* flag);
102 ~WeakReference();
103
104 bool is_valid() const;
105
106 private:
107 scoped_refptr<const Flag> flag_;
108};
109
Vitaly Bukaf2f26402015-08-25 13:03:27 -0700110class BASE_EXPORT WeakReferenceOwner {
Vitaly Bukacbed2062015-08-17 12:54:05 -0700111 public:
112 WeakReferenceOwner();
113 ~WeakReferenceOwner();
114
115 WeakReference GetRef() const;
116
117 bool HasRefs() const {
118 return flag_.get() && !flag_->HasOneRef();
119 }
120
121 void Invalidate();
122
123 private:
124 mutable scoped_refptr<WeakReference::Flag> flag_;
125};
126
127// This class simplifies the implementation of WeakPtr's type conversion
128// constructor by avoiding the need for a public accessor for ref_. A
129// WeakPtr<T> cannot access the private members of WeakPtr<U>, so this
130// base class gives us a way to access ref_ in a protected fashion.
Vitaly Bukaf2f26402015-08-25 13:03:27 -0700131class BASE_EXPORT WeakPtrBase {
Vitaly Bukacbed2062015-08-17 12:54:05 -0700132 public:
133 WeakPtrBase();
134 ~WeakPtrBase();
135
136 protected:
137 explicit WeakPtrBase(const WeakReference& ref);
138
139 WeakReference ref_;
140};
141
142// This class provides a common implementation of common functions that would
143// otherwise get instantiated separately for each distinct instantiation of
144// SupportsWeakPtr<>.
145class SupportsWeakPtrBase {
146 public:
147 // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This
148 // conversion will only compile if there is exists a Base which inherits
149 // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper
150 // function that makes calling this easier.
151 template<typename Derived>
152 static WeakPtr<Derived> StaticAsWeakPtr(Derived* t) {
Vitaly Buka8750b272015-08-18 18:39:08 -0700153 typedef std::is_convertible<Derived*, internal::SupportsWeakPtrBase*>
154 convertible;
Vitaly Bukacbed2062015-08-17 12:54:05 -0700155 COMPILE_ASSERT(convertible::value,
156 AsWeakPtr_argument_inherits_from_SupportsWeakPtr);
157 return AsWeakPtrImpl<Derived>(t, *t);
158 }
159
160 private:
161 // This template function uses type inference to find a Base of Derived
162 // which is an instance of SupportsWeakPtr<Base>. We can then safely
163 // static_cast the Base* to a Derived*.
164 template <typename Derived, typename Base>
165 static WeakPtr<Derived> AsWeakPtrImpl(
166 Derived* t, const SupportsWeakPtr<Base>&) {
167 WeakPtr<Base> ptr = t->Base::AsWeakPtr();
168 return WeakPtr<Derived>(ptr.ref_, static_cast<Derived*>(ptr.ptr_));
169 }
170};
171
172} // namespace internal
173
174template <typename T> class WeakPtrFactory;
175
176// The WeakPtr class holds a weak reference to |T*|.
177//
178// This class is designed to be used like a normal pointer. You should always
179// null-test an object of this class before using it or invoking a method that
180// may result in the underlying object being destroyed.
181//
182// EXAMPLE:
183//
184// class Foo { ... };
185// WeakPtr<Foo> foo;
186// if (foo)
187// foo->method();
188//
189template <typename T>
190class WeakPtr : public internal::WeakPtrBase {
191 public:
192 WeakPtr() : ptr_(NULL) {
193 }
194
195 // Allow conversion from U to T provided U "is a" T. Note that this
196 // is separate from the (implicit) copy constructor.
197 template <typename U>
198 WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other), ptr_(other.ptr_) {
199 }
200
201 T* get() const { return ref_.is_valid() ? ptr_ : NULL; }
202
203 T& operator*() const {
204 DCHECK(get() != NULL);
205 return *get();
206 }
207 T* operator->() const {
208 DCHECK(get() != NULL);
209 return get();
210 }
211
212 // Allow WeakPtr<element_type> to be used in boolean expressions, but not
213 // implicitly convertible to a real bool (which is dangerous).
214 //
215 // Note that this trick is only safe when the == and != operators
216 // are declared explicitly, as otherwise "weak_ptr1 == weak_ptr2"
217 // will compile but do the wrong thing (i.e., convert to Testable
218 // and then do the comparison).
219 private:
220 typedef T* WeakPtr::*Testable;
221
222 public:
223 operator Testable() const { return get() ? &WeakPtr::ptr_ : NULL; }
224
225 void reset() {
226 ref_ = internal::WeakReference();
227 ptr_ = NULL;
228 }
229
230 private:
231 // Explicitly declare comparison operators as required by the bool
232 // trick, but keep them private.
233 template <class U> bool operator==(WeakPtr<U> const&) const;
234 template <class U> bool operator!=(WeakPtr<U> const&) const;
235
236 friend class internal::SupportsWeakPtrBase;
237 template <typename U> friend class WeakPtr;
238 friend class SupportsWeakPtr<T>;
239 friend class WeakPtrFactory<T>;
240
241 WeakPtr(const internal::WeakReference& ref, T* ptr)
242 : WeakPtrBase(ref),
243 ptr_(ptr) {
244 }
245
246 // This pointer is only valid when ref_.is_valid() is true. Otherwise, its
247 // value is undefined (as opposed to NULL).
248 T* ptr_;
249};
250
251// A class may be composed of a WeakPtrFactory and thereby
252// control how it exposes weak pointers to itself. This is helpful if you only
253// need weak pointers within the implementation of a class. This class is also
254// useful when working with primitive types. For example, you could have a
255// WeakPtrFactory<bool> that is used to pass around a weak reference to a bool.
256template <class T>
257class WeakPtrFactory {
258 public:
259 explicit WeakPtrFactory(T* ptr) : ptr_(ptr) {
260 }
261
262 ~WeakPtrFactory() {
263 ptr_ = NULL;
264 }
265
266 WeakPtr<T> GetWeakPtr() {
267 DCHECK(ptr_);
268 return WeakPtr<T>(weak_reference_owner_.GetRef(), ptr_);
269 }
270
271 // Call this method to invalidate all existing weak pointers.
272 void InvalidateWeakPtrs() {
273 DCHECK(ptr_);
274 weak_reference_owner_.Invalidate();
275 }
276
277 // Call this method to determine if any weak pointers exist.
278 bool HasWeakPtrs() const {
279 DCHECK(ptr_);
280 return weak_reference_owner_.HasRefs();
281 }
282
283 private:
284 internal::WeakReferenceOwner weak_reference_owner_;
285 T* ptr_;
286 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory);
287};
288
289// A class may extend from SupportsWeakPtr to let others take weak pointers to
290// it. This avoids the class itself implementing boilerplate to dispense weak
291// pointers. However, since SupportsWeakPtr's destructor won't invalidate
292// weak pointers to the class until after the derived class' members have been
293// destroyed, its use can lead to subtle use-after-destroy issues.
294template <class T>
295class SupportsWeakPtr : public internal::SupportsWeakPtrBase {
296 public:
297 SupportsWeakPtr() {}
298
299 WeakPtr<T> AsWeakPtr() {
300 return WeakPtr<T>(weak_reference_owner_.GetRef(), static_cast<T*>(this));
301 }
302
303 protected:
304 ~SupportsWeakPtr() {}
305
306 private:
307 internal::WeakReferenceOwner weak_reference_owner_;
308 DISALLOW_COPY_AND_ASSIGN(SupportsWeakPtr);
309};
310
311// Helper function that uses type deduction to safely return a WeakPtr<Derived>
312// when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it
313// extends a Base that extends SupportsWeakPtr<Base>.
314//
315// EXAMPLE:
316// class Base : public base::SupportsWeakPtr<Producer> {};
317// class Derived : public Base {};
318//
319// Derived derived;
320// base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived);
321//
322// Note that the following doesn't work (invalid type conversion) since
323// Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(),
324// and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at
325// the caller.
326//
327// base::WeakPtr<Derived> ptr = derived.AsWeakPtr(); // Fails.
328
329template <typename Derived>
330WeakPtr<Derived> AsWeakPtr(Derived* t) {
331 return internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t);
332}
333
334} // namespace base
335
336#endif // BASE_MEMORY_WEAK_PTR_H_