Remove linux_chromium_gn_dbg from the chromium CQ.
[chromium-blink-merge.git] / base / memory / weak_ptr.h
blob1230ead14bf76513cfbc63e22a855db35ac91787
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 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.
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.
15 // EXAMPLE:
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 // };
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 // };
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.
49 // ------------------------- IMPORTANT: Thread-safety -------------------------
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.
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.
62 // Invalidating the factory's WeakPtrs un-binds it from the sequence, allowing
63 // it to be passed for a different sequence to use or delete it.
65 #ifndef BASE_MEMORY_WEAK_PTR_H_
66 #define BASE_MEMORY_WEAK_PTR_H_
68 #include "base/basictypes.h"
69 #include "base/base_export.h"
70 #include "base/logging.h"
71 #include "base/memory/ref_counted.h"
72 #include "base/sequence_checker.h"
73 #include "base/template_util.h"
75 namespace base {
77 template <typename T> class SupportsWeakPtr;
78 template <typename T> class WeakPtr;
80 namespace internal {
81 // These classes are part of the WeakPtr implementation.
82 // DO NOT USE THESE CLASSES DIRECTLY YOURSELF.
84 class BASE_EXPORT WeakReference {
85 public:
86 // Although Flag is bound to a specific SequencedTaskRunner, it may be
87 // deleted from another via base::WeakPtr::~WeakPtr().
88 class BASE_EXPORT Flag : public RefCountedThreadSafe<Flag> {
89 public:
90 Flag();
92 void Invalidate();
93 bool IsValid() const;
95 private:
96 friend class base::RefCountedThreadSafe<Flag>;
98 ~Flag();
100 SequenceChecker sequence_checker_;
101 bool is_valid_;
104 WeakReference();
105 explicit WeakReference(const Flag* flag);
106 ~WeakReference();
108 bool is_valid() const;
110 private:
111 scoped_refptr<const Flag> flag_;
114 class BASE_EXPORT WeakReferenceOwner {
115 public:
116 WeakReferenceOwner();
117 ~WeakReferenceOwner();
119 WeakReference GetRef() const;
121 bool HasRefs() const {
122 return flag_.get() && !flag_->HasOneRef();
125 void Invalidate();
127 private:
128 mutable scoped_refptr<WeakReference::Flag> flag_;
131 // This class simplifies the implementation of WeakPtr's type conversion
132 // constructor by avoiding the need for a public accessor for ref_. A
133 // WeakPtr<T> cannot access the private members of WeakPtr<U>, so this
134 // base class gives us a way to access ref_ in a protected fashion.
135 class BASE_EXPORT WeakPtrBase {
136 public:
137 WeakPtrBase();
138 ~WeakPtrBase();
140 protected:
141 explicit WeakPtrBase(const WeakReference& ref);
143 WeakReference ref_;
146 // This class provides a common implementation of common functions that would
147 // otherwise get instantiated separately for each distinct instantiation of
148 // SupportsWeakPtr<>.
149 class SupportsWeakPtrBase {
150 public:
151 // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This
152 // conversion will only compile if there is exists a Base which inherits
153 // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper
154 // function that makes calling this easier.
155 template<typename Derived>
156 static WeakPtr<Derived> StaticAsWeakPtr(Derived* t) {
157 typedef
158 is_convertible<Derived, internal::SupportsWeakPtrBase&> convertible;
159 COMPILE_ASSERT(convertible::value,
160 AsWeakPtr_argument_inherits_from_SupportsWeakPtr);
161 return AsWeakPtrImpl<Derived>(t, *t);
164 private:
165 // This template function uses type inference to find a Base of Derived
166 // which is an instance of SupportsWeakPtr<Base>. We can then safely
167 // static_cast the Base* to a Derived*.
168 template <typename Derived, typename Base>
169 static WeakPtr<Derived> AsWeakPtrImpl(
170 Derived* t, const SupportsWeakPtr<Base>&) {
171 WeakPtr<Base> ptr = t->Base::AsWeakPtr();
172 return WeakPtr<Derived>(ptr.ref_, static_cast<Derived*>(ptr.ptr_));
176 } // namespace internal
178 template <typename T> class WeakPtrFactory;
180 // The WeakPtr class holds a weak reference to |T*|.
182 // This class is designed to be used like a normal pointer. You should always
183 // null-test an object of this class before using it or invoking a method that
184 // may result in the underlying object being destroyed.
186 // EXAMPLE:
188 // class Foo { ... };
189 // WeakPtr<Foo> foo;
190 // if (foo)
191 // foo->method();
193 template <typename T>
194 class WeakPtr : public internal::WeakPtrBase {
195 public:
196 WeakPtr() : ptr_(NULL) {
199 // Allow conversion from U to T provided U "is a" T. Note that this
200 // is separate from the (implicit) copy constructor.
201 template <typename U>
202 WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other), ptr_(other.ptr_) {
205 T* get() const { return ref_.is_valid() ? ptr_ : NULL; }
207 T& operator*() const {
208 DCHECK(get() != NULL);
209 return *get();
211 T* operator->() const {
212 DCHECK(get() != NULL);
213 return get();
216 // Allow WeakPtr<element_type> to be used in boolean expressions, but not
217 // implicitly convertible to a real bool (which is dangerous).
219 // Note that this trick is only safe when the == and != operators
220 // are declared explicitly, as otherwise "weak_ptr1 == weak_ptr2"
221 // will compile but do the wrong thing (i.e., convert to Testable
222 // and then do the comparison).
223 private:
224 typedef T* WeakPtr::*Testable;
226 public:
227 operator Testable() const { return get() ? &WeakPtr::ptr_ : NULL; }
229 void reset() {
230 ref_ = internal::WeakReference();
231 ptr_ = NULL;
234 private:
235 // Explicitly declare comparison operators as required by the bool
236 // trick, but keep them private.
237 template <class U> bool operator==(WeakPtr<U> const&) const;
238 template <class U> bool operator!=(WeakPtr<U> const&) const;
240 friend class internal::SupportsWeakPtrBase;
241 template <typename U> friend class WeakPtr;
242 friend class SupportsWeakPtr<T>;
243 friend class WeakPtrFactory<T>;
245 WeakPtr(const internal::WeakReference& ref, T* ptr)
246 : WeakPtrBase(ref),
247 ptr_(ptr) {
250 // This pointer is only valid when ref_.is_valid() is true. Otherwise, its
251 // value is undefined (as opposed to NULL).
252 T* ptr_;
255 // A class may be composed of a WeakPtrFactory and thereby
256 // control how it exposes weak pointers to itself. This is helpful if you only
257 // need weak pointers within the implementation of a class. This class is also
258 // useful when working with primitive types. For example, you could have a
259 // WeakPtrFactory<bool> that is used to pass around a weak reference to a bool.
260 template <class T>
261 class WeakPtrFactory {
262 public:
263 explicit WeakPtrFactory(T* ptr) : ptr_(ptr) {
266 ~WeakPtrFactory() {
267 ptr_ = NULL;
270 WeakPtr<T> GetWeakPtr() {
271 DCHECK(ptr_);
272 return WeakPtr<T>(weak_reference_owner_.GetRef(), ptr_);
275 // Call this method to invalidate all existing weak pointers.
276 void InvalidateWeakPtrs() {
277 DCHECK(ptr_);
278 weak_reference_owner_.Invalidate();
281 // Call this method to determine if any weak pointers exist.
282 bool HasWeakPtrs() const {
283 DCHECK(ptr_);
284 return weak_reference_owner_.HasRefs();
287 private:
288 internal::WeakReferenceOwner weak_reference_owner_;
289 T* ptr_;
290 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory);
293 // A class may extend from SupportsWeakPtr to let others take weak pointers to
294 // it. This avoids the class itself implementing boilerplate to dispense weak
295 // pointers. However, since SupportsWeakPtr's destructor won't invalidate
296 // weak pointers to the class until after the derived class' members have been
297 // destroyed, its use can lead to subtle use-after-destroy issues.
298 template <class T>
299 class SupportsWeakPtr : public internal::SupportsWeakPtrBase {
300 public:
301 SupportsWeakPtr() {}
303 WeakPtr<T> AsWeakPtr() {
304 return WeakPtr<T>(weak_reference_owner_.GetRef(), static_cast<T*>(this));
307 protected:
308 ~SupportsWeakPtr() {}
310 private:
311 internal::WeakReferenceOwner weak_reference_owner_;
312 DISALLOW_COPY_AND_ASSIGN(SupportsWeakPtr);
315 // Helper function that uses type deduction to safely return a WeakPtr<Derived>
316 // when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it
317 // extends a Base that extends SupportsWeakPtr<Base>.
319 // EXAMPLE:
320 // class Base : public base::SupportsWeakPtr<Producer> {};
321 // class Derived : public Base {};
323 // Derived derived;
324 // base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived);
326 // Note that the following doesn't work (invalid type conversion) since
327 // Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(),
328 // and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at
329 // the caller.
331 // base::WeakPtr<Derived> ptr = derived.AsWeakPtr(); // Fails.
333 template <typename Derived>
334 WeakPtr<Derived> AsWeakPtr(Derived* t) {
335 return internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t);
338 } // namespace base
340 #endif // BASE_MEMORY_WEAK_PTR_H_