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