blob: f6001e2a16928f3e97307a157ed651412e17dac1 [file] [log] [blame]
[email protected]7f18b7c42012-02-24 09:13:091// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]3125d6462009-09-01 20:50:172// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]2c691392013-04-25 20:47:185// 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
[email protected]3125d6462009-09-01 20:50:1715// EXAMPLE:
16//
[email protected]2c691392013-04-25 20:47:1817// class Controller {
[email protected]3125d6462009-09-01 20:50:1718// public:
[email protected]2c691392013-04-25 20:47:1819// void SpawnWorker() { Worker::StartNew(weak_factory_.GetWeakPtr()); }
[email protected]3125d6462009-09-01 20:50:1720// void WorkComplete(const Result& result) { ... }
[email protected]2c691392013-04-25 20:47:1821// private:
[email protected]ed3f67342013-05-29 08:04:3222// // 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.
[email protected]2c691392013-04-25 20:47:1825// WeakPtrFactory<Controller> weak_factory_;
[email protected]3125d6462009-09-01 20:50:1726// };
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//
[email protected]2c691392013-04-25 20:47:1844// 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
[email protected]ed3f67342013-05-29 08:04:3250// Weak pointers may be passed safely between threads, but must always be
51// dereferenced and invalidated on the same thread otherwise checking the
52// 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, and cannot be dereferenced or invalidated on any other thread. Bound
57// WeakPtrs can still be handed off to other threads, e.g. to use to post tasks
58// back to object on the bound thread.
59//
60// Invalidating the factory's WeakPtrs un-binds it from the thread, allowing it
61// to be passed for a different thread to use or delete it.
[email protected]3125d6462009-09-01 20:50:1762
[email protected]3b63f8f42011-03-28 01:54:1563#ifndef BASE_MEMORY_WEAK_PTR_H_
64#define BASE_MEMORY_WEAK_PTR_H_
[email protected]3125d6462009-09-01 20:50:1765
[email protected]4c44b8442012-06-15 16:36:1266#include "base/basictypes.h"
[email protected]0bea7252011-08-05 15:34:0067#include "base/base_export.h"
[email protected]3125d6462009-09-01 20:50:1768#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1569#include "base/memory/ref_counted.h"
[email protected]d52426c2013-07-30 19:26:4070#include "base/sequence_checker.h"
[email protected]4c44b8442012-06-15 16:36:1271#include "base/template_util.h"
[email protected]3125d6462009-09-01 20:50:1772
73namespace base {
74
[email protected]4c44b8442012-06-15 16:36:1275template <typename T> class SupportsWeakPtr;
76template <typename T> class WeakPtr;
77
[email protected]3125d6462009-09-01 20:50:1778namespace internal {
79// These classes are part of the WeakPtr implementation.
80// DO NOT USE THESE CLASSES DIRECTLY YOURSELF.
81
[email protected]0bea7252011-08-05 15:34:0082class BASE_EXPORT WeakReference {
[email protected]3125d6462009-09-01 20:50:1783 public:
[email protected]ed3f67342013-05-29 08:04:3284 // Although Flag is bound to a specific thread, it may be deleted from another
[email protected]05b1cd612011-04-11 20:47:2585 // via base::WeakPtr::~WeakPtr().
[email protected]a827a562014-06-11 00:37:4286 class BASE_EXPORT Flag : public RefCountedThreadSafe<Flag> {
[email protected]d52e9702009-09-17 00:31:0987 public:
[email protected]1edefc42011-08-26 17:32:2988 Flag();
[email protected]59326aac2009-09-25 23:34:3489
[email protected]6aacd8d2011-03-10 19:56:5390 void Invalidate();
91 bool IsValid() const;
[email protected]59326aac2009-09-25 23:34:3492
93 private:
[email protected]05b1cd612011-04-11 20:47:2594 friend class base::RefCountedThreadSafe<Flag>;
95
96 ~Flag();
97
[email protected]d52426c2013-07-30 19:26:4098 SequenceChecker sequence_checker_;
[email protected]1edefc42011-08-26 17:32:2999 bool is_valid_;
[email protected]3125d6462009-09-01 20:50:17100 };
101
[email protected]3a3d47472010-07-15 21:03:54102 WeakReference();
[email protected]1edefc42011-08-26 17:32:29103 explicit WeakReference(const Flag* flag);
[email protected]201366472010-07-16 17:22:49104 ~WeakReference();
[email protected]59326aac2009-09-25 23:34:34105
[email protected]3a3d47472010-07-15 21:03:54106 bool is_valid() const;
[email protected]59326aac2009-09-25 23:34:34107
108 private:
[email protected]1edefc42011-08-26 17:32:29109 scoped_refptr<const Flag> flag_;
[email protected]3125d6462009-09-01 20:50:17110};
111
[email protected]0bea7252011-08-05 15:34:00112class BASE_EXPORT WeakReferenceOwner {
[email protected]3125d6462009-09-01 20:50:17113 public:
[email protected]3a3d47472010-07-15 21:03:54114 WeakReferenceOwner();
115 ~WeakReferenceOwner();
[email protected]59326aac2009-09-25 23:34:34116
[email protected]3a3d47472010-07-15 21:03:54117 WeakReference GetRef() const;
[email protected]3125d6462009-09-01 20:50:17118
[email protected]59326aac2009-09-25 23:34:34119 bool HasRefs() const {
[email protected]1edefc42011-08-26 17:32:29120 return flag_.get() && !flag_->HasOneRef();
[email protected]59326aac2009-09-25 23:34:34121 }
122
[email protected]3a3d47472010-07-15 21:03:54123 void Invalidate();
[email protected]3125d6462009-09-01 20:50:17124
125 private:
[email protected]1edefc42011-08-26 17:32:29126 mutable scoped_refptr<WeakReference::Flag> flag_;
[email protected]3125d6462009-09-01 20:50:17127};
128
129// This class simplifies the implementation of WeakPtr's type conversion
130// constructor by avoiding the need for a public accessor for ref_. A
131// WeakPtr<T> cannot access the private members of WeakPtr<U>, so this
132// base class gives us a way to access ref_ in a protected fashion.
[email protected]0bea7252011-08-05 15:34:00133class BASE_EXPORT WeakPtrBase {
[email protected]3125d6462009-09-01 20:50:17134 public:
[email protected]3a3d47472010-07-15 21:03:54135 WeakPtrBase();
[email protected]201366472010-07-16 17:22:49136 ~WeakPtrBase();
[email protected]3125d6462009-09-01 20:50:17137
138 protected:
[email protected]4c44b8442012-06-15 16:36:12139 explicit WeakPtrBase(const WeakReference& ref);
[email protected]3125d6462009-09-01 20:50:17140
141 WeakReference ref_;
142};
143
[email protected]4c44b8442012-06-15 16:36:12144// This class provides a common implementation of common functions that would
145// otherwise get instantiated separately for each distinct instantiation of
146// SupportsWeakPtr<>.
147class SupportsWeakPtrBase {
148 public:
149 // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This
150 // conversion will only compile if there is exists a Base which inherits
151 // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper
152 // function that makes calling this easier.
153 template<typename Derived>
154 static WeakPtr<Derived> StaticAsWeakPtr(Derived* t) {
155 typedef
156 is_convertible<Derived, internal::SupportsWeakPtrBase&> convertible;
157 COMPILE_ASSERT(convertible::value,
158 AsWeakPtr_argument_inherits_from_SupportsWeakPtr);
159 return AsWeakPtrImpl<Derived>(t, *t);
160 }
161
162 private:
163 // This template function uses type inference to find a Base of Derived
164 // which is an instance of SupportsWeakPtr<Base>. We can then safely
165 // static_cast the Base* to a Derived*.
166 template <typename Derived, typename Base>
167 static WeakPtr<Derived> AsWeakPtrImpl(
168 Derived* t, const SupportsWeakPtr<Base>&) {
169 WeakPtr<Base> ptr = t->Base::AsWeakPtr();
170 return WeakPtr<Derived>(ptr.ref_, static_cast<Derived*>(ptr.ptr_));
171 }
172};
173
[email protected]3125d6462009-09-01 20:50:17174} // namespace internal
175
[email protected]3125d6462009-09-01 20:50:17176template <typename T> class WeakPtrFactory;
177
178// The WeakPtr class holds a weak reference to |T*|.
179//
180// This class is designed to be used like a normal pointer. You should always
181// null-test an object of this class before using it or invoking a method that
182// may result in the underlying object being destroyed.
183//
184// EXAMPLE:
185//
186// class Foo { ... };
187// WeakPtr<Foo> foo;
188// if (foo)
189// foo->method();
190//
191template <typename T>
192class WeakPtr : public internal::WeakPtrBase {
193 public:
194 WeakPtr() : ptr_(NULL) {
195 }
196
[email protected]c33acdb2013-03-02 02:31:45197 // Allow conversion from U to T provided U "is a" T. Note that this
198 // is separate from the (implicit) copy constructor.
[email protected]3125d6462009-09-01 20:50:17199 template <typename U>
[email protected]c33acdb2013-03-02 02:31:45200 WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other), ptr_(other.ptr_) {
[email protected]3125d6462009-09-01 20:50:17201 }
202
203 T* get() const { return ref_.is_valid() ? ptr_ : NULL; }
[email protected]3125d6462009-09-01 20:50:17204
[email protected]f1836f42012-02-29 06:59:03205 T& operator*() const {
[email protected]3125d6462009-09-01 20:50:17206 DCHECK(get() != NULL);
[email protected]f1836f42012-02-29 06:59:03207 return *get();
[email protected]3125d6462009-09-01 20:50:17208 }
209 T* operator->() const {
210 DCHECK(get() != NULL);
211 return get();
212 }
213
[email protected]380b1392013-06-06 05:32:37214 // Allow WeakPtr<element_type> to be used in boolean expressions, but not
215 // implicitly convertible to a real bool (which is dangerous).
216 //
217 // Note that this trick is only safe when the == and != operators
218 // are declared explicitly, as otherwise "weak_ptr1 == weak_ptr2"
219 // will compile but do the wrong thing (i.e., convert to Testable
220 // and then do the comparison).
221 private:
222 typedef T* WeakPtr::*Testable;
223
224 public:
225 operator Testable() const { return get() ? &WeakPtr::ptr_ : NULL; }
226
[email protected]f103ab72009-09-02 17:10:59227 void reset() {
228 ref_ = internal::WeakReference();
229 ptr_ = NULL;
230 }
231
[email protected]3125d6462009-09-01 20:50:17232 private:
[email protected]380b1392013-06-06 05:32:37233 // Explicitly declare comparison operators as required by the bool
234 // trick, but keep them private.
235 template <class U> bool operator==(WeakPtr<U> const&) const;
236 template <class U> bool operator!=(WeakPtr<U> const&) const;
237
[email protected]4c44b8442012-06-15 16:36:12238 friend class internal::SupportsWeakPtrBase;
[email protected]c33acdb2013-03-02 02:31:45239 template <typename U> friend class WeakPtr;
[email protected]3125d6462009-09-01 20:50:17240 friend class SupportsWeakPtr<T>;
241 friend class WeakPtrFactory<T>;
242
243 WeakPtr(const internal::WeakReference& ref, T* ptr)
[email protected]5d6688f2012-07-11 21:39:03244 : WeakPtrBase(ref),
245 ptr_(ptr) {
[email protected]3125d6462009-09-01 20:50:17246 }
247
248 // This pointer is only valid when ref_.is_valid() is true. Otherwise, its
249 // value is undefined (as opposed to NULL).
250 T* ptr_;
251};
252
[email protected]2c691392013-04-25 20:47:18253// A class may be composed of a WeakPtrFactory and thereby
254// control how it exposes weak pointers to itself. This is helpful if you only
255// need weak pointers within the implementation of a class. This class is also
256// useful when working with primitive types. For example, you could have a
257// WeakPtrFactory<bool> that is used to pass around a weak reference to a bool.
258template <class T>
259class WeakPtrFactory {
260 public:
261 explicit WeakPtrFactory(T* ptr) : ptr_(ptr) {
262 }
263
264 ~WeakPtrFactory() {
265 ptr_ = NULL;
266 }
267
268 WeakPtr<T> GetWeakPtr() {
269 DCHECK(ptr_);
270 return WeakPtr<T>(weak_reference_owner_.GetRef(), ptr_);
271 }
272
273 // Call this method to invalidate all existing weak pointers.
274 void InvalidateWeakPtrs() {
275 DCHECK(ptr_);
276 weak_reference_owner_.Invalidate();
277 }
278
279 // Call this method to determine if any weak pointers exist.
280 bool HasWeakPtrs() const {
281 DCHECK(ptr_);
282 return weak_reference_owner_.HasRefs();
283 }
284
[email protected]2c691392013-04-25 20:47:18285 private:
286 internal::WeakReferenceOwner weak_reference_owner_;
287 T* ptr_;
288 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory);
289};
290
291// A class may extend from SupportsWeakPtr to let others take weak pointers to
292// it. This avoids the class itself implementing boilerplate to dispense weak
293// pointers. However, since SupportsWeakPtr's destructor won't invalidate
294// weak pointers to the class until after the derived class' members have been
295// destroyed, its use can lead to subtle use-after-destroy issues.
[email protected]3125d6462009-09-01 20:50:17296template <class T>
[email protected]4c44b8442012-06-15 16:36:12297class SupportsWeakPtr : public internal::SupportsWeakPtrBase {
[email protected]3125d6462009-09-01 20:50:17298 public:
299 SupportsWeakPtr() {}
300
301 WeakPtr<T> AsWeakPtr() {
302 return WeakPtr<T>(weak_reference_owner_.GetRef(), static_cast<T*>(this));
303 }
304
[email protected]cb932482012-06-26 06:23:00305 protected:
306 ~SupportsWeakPtr() {}
307
[email protected]3125d6462009-09-01 20:50:17308 private:
309 internal::WeakReferenceOwner weak_reference_owner_;
310 DISALLOW_COPY_AND_ASSIGN(SupportsWeakPtr);
311};
312
[email protected]4c44b8442012-06-15 16:36:12313// Helper function that uses type deduction to safely return a WeakPtr<Derived>
314// when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it
315// extends a Base that extends SupportsWeakPtr<Base>.
316//
317// EXAMPLE:
318// class Base : public base::SupportsWeakPtr<Producer> {};
319// class Derived : public Base {};
320//
321// Derived derived;
322// base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived);
323//
324// Note that the following doesn't work (invalid type conversion) since
325// Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(),
326// and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at
327// the caller.
328//
329// base::WeakPtr<Derived> ptr = derived.AsWeakPtr(); // Fails.
330
331template <typename Derived>
332WeakPtr<Derived> AsWeakPtr(Derived* t) {
333 return internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t);
334}
335
[email protected]3125d6462009-09-01 20:50:17336} // namespace base
337
[email protected]3b63f8f42011-03-28 01:54:15338#endif // BASE_MEMORY_WEAK_PTR_H_