weak_ptr.h revision 90dce4d38c5ff5333bea97d859d4e484e27edf0c
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_) flag_->DetachFromThreadHack();
131  }
132
133 private:
134  mutable scoped_refptr<WeakReference::Flag> flag_;
135};
136
137// This class simplifies the implementation of WeakPtr's type conversion
138// constructor by avoiding the need for a public accessor for ref_.  A
139// WeakPtr<T> cannot access the private members of WeakPtr<U>, so this
140// base class gives us a way to access ref_ in a protected fashion.
141class BASE_EXPORT WeakPtrBase {
142 public:
143  WeakPtrBase();
144  ~WeakPtrBase();
145
146 protected:
147  explicit WeakPtrBase(const WeakReference& ref);
148
149  WeakReference ref_;
150};
151
152// This class provides a common implementation of common functions that would
153// otherwise get instantiated separately for each distinct instantiation of
154// SupportsWeakPtr<>.
155class SupportsWeakPtrBase {
156 public:
157  // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This
158  // conversion will only compile if there is exists a Base which inherits
159  // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper
160  // function that makes calling this easier.
161  template<typename Derived>
162  static WeakPtr<Derived> StaticAsWeakPtr(Derived* t) {
163    typedef
164        is_convertible<Derived, internal::SupportsWeakPtrBase&> convertible;
165    COMPILE_ASSERT(convertible::value,
166                   AsWeakPtr_argument_inherits_from_SupportsWeakPtr);
167    return AsWeakPtrImpl<Derived>(t, *t);
168  }
169
170 private:
171  // This template function uses type inference to find a Base of Derived
172  // which is an instance of SupportsWeakPtr<Base>. We can then safely
173  // static_cast the Base* to a Derived*.
174  template <typename Derived, typename Base>
175  static WeakPtr<Derived> AsWeakPtrImpl(
176      Derived* t, const SupportsWeakPtr<Base>&) {
177    WeakPtr<Base> ptr = t->Base::AsWeakPtr();
178    return WeakPtr<Derived>(ptr.ref_, static_cast<Derived*>(ptr.ptr_));
179  }
180};
181
182}  // namespace internal
183
184template <typename T> class WeakPtrFactory;
185
186// The WeakPtr class holds a weak reference to |T*|.
187//
188// This class is designed to be used like a normal pointer.  You should always
189// null-test an object of this class before using it or invoking a method that
190// may result in the underlying object being destroyed.
191//
192// EXAMPLE:
193//
194//   class Foo { ... };
195//   WeakPtr<Foo> foo;
196//   if (foo)
197//     foo->method();
198//
199template <typename T>
200class WeakPtr : public internal::WeakPtrBase {
201 public:
202  WeakPtr() : ptr_(NULL) {
203  }
204
205  // Allow conversion from U to T provided U "is a" T. Note that this
206  // is separate from the (implicit) copy constructor.
207  template <typename U>
208  WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other), ptr_(other.ptr_) {
209  }
210
211  T* get() const { return ref_.is_valid() ? ptr_ : NULL; }
212  operator T*() const { return get(); }
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  void reset() {
224    ref_ = internal::WeakReference();
225    ptr_ = NULL;
226  }
227
228 private:
229  friend class internal::SupportsWeakPtrBase;
230  template <typename U> friend class WeakPtr;
231  friend class SupportsWeakPtr<T>;
232  friend class WeakPtrFactory<T>;
233
234  WeakPtr(const internal::WeakReference& ref, T* ptr)
235      : WeakPtrBase(ref),
236        ptr_(ptr) {
237  }
238
239  // This pointer is only valid when ref_.is_valid() is true.  Otherwise, its
240  // value is undefined (as opposed to NULL).
241  T* ptr_;
242};
243
244// A class may be composed of a WeakPtrFactory and thereby
245// control how it exposes weak pointers to itself.  This is helpful if you only
246// need weak pointers within the implementation of a class.  This class is also
247// useful when working with primitive types.  For example, you could have a
248// WeakPtrFactory<bool> that is used to pass around a weak reference to a bool.
249template <class T>
250class WeakPtrFactory {
251 public:
252  explicit WeakPtrFactory(T* ptr) : ptr_(ptr) {
253  }
254
255  ~WeakPtrFactory() {
256    ptr_ = NULL;
257  }
258
259  WeakPtr<T> GetWeakPtr() {
260    DCHECK(ptr_);
261    return WeakPtr<T>(weak_reference_owner_.GetRef(), ptr_);
262  }
263
264  // Call this method to invalidate all existing weak pointers.
265  void InvalidateWeakPtrs() {
266    DCHECK(ptr_);
267    weak_reference_owner_.Invalidate();
268  }
269
270  // Call this method to determine if any weak pointers exist.
271  bool HasWeakPtrs() const {
272    DCHECK(ptr_);
273    return weak_reference_owner_.HasRefs();
274  }
275
276 private:
277  internal::WeakReferenceOwner weak_reference_owner_;
278  T* ptr_;
279  DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory);
280};
281
282// A class may extend from SupportsWeakPtr to let others take weak pointers to
283// it. This avoids the class itself implementing boilerplate to dispense weak
284// pointers.  However, since SupportsWeakPtr's destructor won't invalidate
285// weak pointers to the class until after the derived class' members have been
286// destroyed, its use can lead to subtle use-after-destroy issues.
287template <class T>
288class SupportsWeakPtr : public internal::SupportsWeakPtrBase {
289 public:
290  SupportsWeakPtr() {}
291
292  WeakPtr<T> AsWeakPtr() {
293    return WeakPtr<T>(weak_reference_owner_.GetRef(), static_cast<T*>(this));
294  }
295
296  // Removes the binding, if any, from this object to a particular thread.
297  // This is used in WebGraphicsContext3DInProcessCommandBufferImpl to work-
298  // around access to cmmand buffer objects by more than one thread.
299  // Remove this when crbug.com/234964 is addressed.
300  void DetachFromThreadHack() {
301    weak_reference_owner_.DetachFromThreadHack();
302  }
303
304 protected:
305  ~SupportsWeakPtr() {}
306
307 private:
308  internal::WeakReferenceOwner weak_reference_owner_;
309  DISALLOW_COPY_AND_ASSIGN(SupportsWeakPtr);
310};
311
312// Helper function that uses type deduction to safely return a WeakPtr<Derived>
313// when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it
314// extends a Base that extends SupportsWeakPtr<Base>.
315//
316// EXAMPLE:
317//   class Base : public base::SupportsWeakPtr<Producer> {};
318//   class Derived : public Base {};
319//
320//   Derived derived;
321//   base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived);
322//
323// Note that the following doesn't work (invalid type conversion) since
324// Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(),
325// and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at
326// the caller.
327//
328//   base::WeakPtr<Derived> ptr = derived.AsWeakPtr();  // Fails.
329
330template <typename Derived>
331WeakPtr<Derived> AsWeakPtr(Derived* t) {
332  return internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t);
333}
334
335}  // namespace base
336
337#endif  // BASE_MEMORY_WEAK_PTR_H_
338