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