Update .DEPS.git
[chromium-blink-merge.git] / base / memory / weak_ptr.h
blob7006fb63e0981468e30ac2c631e8d6c1ed645ef7
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.
5 // Weak pointers help in cases where you have many objects referring back to a
6 // shared object and you wish for the lifetime of the shared object to not be
7 // bound to the lifetime of the referrers. In other words, this is useful when
8 // reference counting is not a good fit.
9 //
10 // A common alternative to weak pointers is to have the shared object hold a
11 // list of all referrers, and then when the shared object is destroyed, it
12 // calls a method on the referrers to tell them to drop their references. This
13 // approach also requires the referrers to tell the shared object when they get
14 // destroyed so that the shared object can remove the referrer from its list of
15 // referrers. Such a solution works, but it is a bit complex.
17 // EXAMPLE:
19 // class Controller : public SupportsWeakPtr<Controller> {
20 // public:
21 // void SpawnWorker() { Worker::StartNew(AsWeakPtr()); }
22 // void WorkComplete(const Result& result) { ... }
23 // };
25 // class Worker {
26 // public:
27 // static void StartNew(const WeakPtr<Controller>& controller) {
28 // Worker* worker = new Worker(controller);
29 // // Kick off asynchronous processing...
30 // }
31 // private:
32 // Worker(const WeakPtr<Controller>& controller)
33 // : controller_(controller) {}
34 // void DidCompleteAsynchronousProcessing(const Result& result) {
35 // if (controller_)
36 // controller_->WorkComplete(result);
37 // }
38 // WeakPtr<Controller> controller_;
39 // };
41 // Given the above classes, a consumer may allocate a Controller object, call
42 // SpawnWorker several times, and then destroy the Controller object before all
43 // of the workers have completed. Because the Worker class only holds a weak
44 // pointer to the Controller, we don't have to worry about the Worker
45 // dereferencing the Controller back pointer after the Controller has been
46 // destroyed.
48 // ------------------------ Thread-safety notes ------------------------
49 // When you get a WeakPtr (from a WeakPtrFactory or SupportsWeakPtr), if it's
50 // the only one pointing to the object, the object become bound to the
51 // current thread, as well as this WeakPtr and all later ones get created.
53 // You may only dereference the WeakPtr on the thread it binds to. However, it
54 // is safe to destroy the WeakPtr object on another thread. Because of this,
55 // querying WeakPtrFactory's HasWeakPtrs() method can be racy.
57 // On the other hand, the object that supports WeakPtr (extends SupportsWeakPtr)
58 // can only be deleted from the thread it binds to, until all WeakPtrs are
59 // deleted.
61 // Calling SupportsWeakPtr::DetachFromThread() can work around the limitations
62 // above and cancel the thread binding of the object and all WeakPtrs pointing
63 // to it, but it's not recommended and unsafe.
65 // WeakPtrs may be copy-constructed or assigned on threads other than the thread
66 // they are bound to. This does not change the thread binding. So these WeakPtrs
67 // may only be dereferenced on the thread that the original WeakPtr was bound
68 // to.
70 #ifndef BASE_MEMORY_WEAK_PTR_H_
71 #define BASE_MEMORY_WEAK_PTR_H_
73 #include "base/basictypes.h"
74 #include "base/base_export.h"
75 #include "base/logging.h"
76 #include "base/memory/ref_counted.h"
77 #include "base/template_util.h"
78 #include "base/threading/thread_checker.h"
80 namespace base {
82 template <typename T> class SupportsWeakPtr;
83 template <typename T> class WeakPtr;
85 namespace internal {
86 // These classes are part of the WeakPtr implementation.
87 // DO NOT USE THESE CLASSES DIRECTLY YOURSELF.
89 class BASE_EXPORT WeakReference {
90 public:
91 // While Flag is bound to a specific thread, it may be deleted from another
92 // via base::WeakPtr::~WeakPtr().
93 class Flag : public RefCountedThreadSafe<Flag> {
94 public:
95 Flag();
97 void Invalidate();
98 bool IsValid() const;
100 void DetachFromThread() { thread_checker_.DetachFromThread(); }
102 private:
103 friend class base::RefCountedThreadSafe<Flag>;
105 ~Flag();
107 ThreadChecker thread_checker_;
108 bool is_valid_;
111 WeakReference();
112 explicit WeakReference(const Flag* flag);
113 ~WeakReference();
115 bool is_valid() const;
117 private:
118 scoped_refptr<const Flag> flag_;
121 class BASE_EXPORT WeakReferenceOwner {
122 public:
123 WeakReferenceOwner();
124 ~WeakReferenceOwner();
126 WeakReference GetRef() const;
128 bool HasRefs() const {
129 return flag_.get() && !flag_->HasOneRef();
132 void Invalidate();
134 // Indicates that this object will be used on another thread from now on.
135 void DetachFromThread() {
136 if (flag_) flag_->DetachFromThread();
139 private:
140 mutable scoped_refptr<WeakReference::Flag> flag_;
143 // This class simplifies the implementation of WeakPtr's type conversion
144 // constructor by avoiding the need for a public accessor for ref_. A
145 // WeakPtr<T> cannot access the private members of WeakPtr<U>, so this
146 // base class gives us a way to access ref_ in a protected fashion.
147 class BASE_EXPORT WeakPtrBase {
148 public:
149 WeakPtrBase();
150 ~WeakPtrBase();
152 protected:
153 explicit WeakPtrBase(const WeakReference& ref);
155 WeakReference ref_;
158 // This class provides a common implementation of common functions that would
159 // otherwise get instantiated separately for each distinct instantiation of
160 // SupportsWeakPtr<>.
161 class SupportsWeakPtrBase {
162 public:
163 // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This
164 // conversion will only compile if there is exists a Base which inherits
165 // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper
166 // function that makes calling this easier.
167 template<typename Derived>
168 static WeakPtr<Derived> StaticAsWeakPtr(Derived* t) {
169 typedef
170 is_convertible<Derived, internal::SupportsWeakPtrBase&> convertible;
171 COMPILE_ASSERT(convertible::value,
172 AsWeakPtr_argument_inherits_from_SupportsWeakPtr);
173 return AsWeakPtrImpl<Derived>(t, *t);
176 private:
177 // This template function uses type inference to find a Base of Derived
178 // which is an instance of SupportsWeakPtr<Base>. We can then safely
179 // static_cast the Base* to a Derived*.
180 template <typename Derived, typename Base>
181 static WeakPtr<Derived> AsWeakPtrImpl(
182 Derived* t, const SupportsWeakPtr<Base>&) {
183 WeakPtr<Base> ptr = t->Base::AsWeakPtr();
184 return WeakPtr<Derived>(ptr.ref_, static_cast<Derived*>(ptr.ptr_));
188 } // namespace internal
190 template <typename T> class WeakPtrFactory;
192 // The WeakPtr class holds a weak reference to |T*|.
194 // This class is designed to be used like a normal pointer. You should always
195 // null-test an object of this class before using it or invoking a method that
196 // may result in the underlying object being destroyed.
198 // EXAMPLE:
200 // class Foo { ... };
201 // WeakPtr<Foo> foo;
202 // if (foo)
203 // foo->method();
205 template <typename T>
206 class WeakPtr : public internal::WeakPtrBase {
207 public:
208 WeakPtr() : ptr_(NULL) {
211 // Allow conversion from U to T provided U "is a" T.
212 template <typename U>
213 WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other), ptr_(other.get()) {
216 T* get() const { return ref_.is_valid() ? ptr_ : NULL; }
217 operator T*() const { return get(); }
219 T& operator*() const {
220 DCHECK(get() != NULL);
221 return *get();
223 T* operator->() const {
224 DCHECK(get() != NULL);
225 return get();
228 void reset() {
229 ref_ = internal::WeakReference();
230 ptr_ = NULL;
233 private:
234 friend class internal::SupportsWeakPtrBase;
235 friend class SupportsWeakPtr<T>;
236 friend class WeakPtrFactory<T>;
238 WeakPtr(const internal::WeakReference& ref, T* ptr)
239 : WeakPtrBase(ref),
240 ptr_(ptr) {
243 // This pointer is only valid when ref_.is_valid() is true. Otherwise, its
244 // value is undefined (as opposed to NULL).
245 T* ptr_;
248 // A class may extend from SupportsWeakPtr to expose weak pointers to itself.
249 // This is useful in cases where you want others to be able to get a weak
250 // pointer to your class. It also has the property that you don't need to
251 // initialize it from your constructor.
252 template <class T>
253 class SupportsWeakPtr : public internal::SupportsWeakPtrBase {
254 public:
255 SupportsWeakPtr() {}
257 WeakPtr<T> AsWeakPtr() {
258 return WeakPtr<T>(weak_reference_owner_.GetRef(), static_cast<T*>(this));
261 // Indicates that this object will be used on another thread from now on.
262 void DetachFromThread() {
263 weak_reference_owner_.DetachFromThread();
266 protected:
267 ~SupportsWeakPtr() {}
269 private:
270 internal::WeakReferenceOwner weak_reference_owner_;
271 DISALLOW_COPY_AND_ASSIGN(SupportsWeakPtr);
274 // Helper function that uses type deduction to safely return a WeakPtr<Derived>
275 // when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it
276 // extends a Base that extends SupportsWeakPtr<Base>.
278 // EXAMPLE:
279 // class Base : public base::SupportsWeakPtr<Producer> {};
280 // class Derived : public Base {};
282 // Derived derived;
283 // base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived);
285 // Note that the following doesn't work (invalid type conversion) since
286 // Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(),
287 // and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at
288 // the caller.
290 // base::WeakPtr<Derived> ptr = derived.AsWeakPtr(); // Fails.
292 template <typename Derived>
293 WeakPtr<Derived> AsWeakPtr(Derived* t) {
294 return internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t);
297 // A class may alternatively 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 {
304 public:
305 explicit WeakPtrFactory(T* ptr) : ptr_(ptr) {
308 ~WeakPtrFactory() {
309 ptr_ = NULL;
312 WeakPtr<T> GetWeakPtr() {
313 DCHECK(ptr_);
314 return WeakPtr<T>(weak_reference_owner_.GetRef(), ptr_);
317 // Call this method to invalidate all existing weak pointers.
318 void InvalidateWeakPtrs() {
319 DCHECK(ptr_);
320 weak_reference_owner_.Invalidate();
323 // Call this method to determine if any weak pointers exist.
324 bool HasWeakPtrs() const {
325 DCHECK(ptr_);
326 return weak_reference_owner_.HasRefs();
329 // Indicates that this object will be used on another thread from now on.
330 void DetachFromThread() {
331 DCHECK(ptr_);
332 weak_reference_owner_.DetachFromThread();
335 private:
336 internal::WeakReferenceOwner weak_reference_owner_;
337 T* ptr_;
338 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory);
341 } // namespace base
343 #endif // BASE_MEMORY_WEAK_PTR_H_