michael@0: // Copyright (c) 2012 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: // Weak pointers are pointers to an object that do not affect its lifetime, michael@0: // and which may be invalidated (i.e. reset to NULL) by the object, or its michael@0: // owner, at any time, most commonly when the object is about to be deleted. michael@0: michael@0: // Weak pointers are useful when an object needs to be accessed safely by one michael@0: // or more objects other than its owner, and those callers can cope with the michael@0: // object vanishing and e.g. tasks posted to it being silently dropped. michael@0: // Reference-counting such an object would complicate the ownership graph and michael@0: // make it harder to reason about the object's lifetime. michael@0: michael@0: // EXAMPLE: michael@0: // michael@0: // class Controller { michael@0: // public: michael@0: // void SpawnWorker() { Worker::StartNew(weak_factory_.GetWeakPtr()); } michael@0: // void WorkComplete(const Result& result) { ... } michael@0: // private: michael@0: // // Member variables should appear before the WeakPtrFactory, to ensure michael@0: // // that any WeakPtrs to Controller are invalidated before its members michael@0: // // variable's destructors are executed, rendering them invalid. michael@0: // WeakPtrFactory weak_factory_; michael@0: // }; michael@0: // michael@0: // class Worker { michael@0: // public: michael@0: // static void StartNew(const WeakPtr& controller) { michael@0: // Worker* worker = new Worker(controller); michael@0: // // Kick off asynchronous processing... michael@0: // } michael@0: // private: michael@0: // Worker(const WeakPtr& controller) michael@0: // : controller_(controller) {} michael@0: // void DidCompleteAsynchronousProcessing(const Result& result) { michael@0: // if (controller_) michael@0: // controller_->WorkComplete(result); michael@0: // } michael@0: // WeakPtr controller_; michael@0: // }; michael@0: // michael@0: // With this implementation a caller may use SpawnWorker() to dispatch multiple michael@0: // Workers and subsequently delete the Controller, without waiting for all michael@0: // Workers to have completed. michael@0: michael@0: // ------------------------- IMPORTANT: Thread-safety ------------------------- michael@0: michael@0: // Weak pointers may be passed safely between threads, but must always be michael@0: // dereferenced and invalidated on the same thread otherwise checking the michael@0: // pointer would be racey. michael@0: // michael@0: // To ensure correct use, the first time a WeakPtr issued by a WeakPtrFactory michael@0: // is dereferenced, the factory and its WeakPtrs become bound to the calling michael@0: // thread, and cannot be dereferenced or invalidated on any other thread. Bound michael@0: // WeakPtrs can still be handed off to other threads, e.g. to use to post tasks michael@0: // back to object on the bound thread. michael@0: // michael@0: // Invalidating the factory's WeakPtrs un-binds it from the thread, allowing it michael@0: // to be passed for a different thread to use or delete it. michael@0: michael@0: #ifndef BASE_MEMORY_WEAK_PTR_H_ michael@0: #define BASE_MEMORY_WEAK_PTR_H_ michael@0: michael@0: #include "base/basictypes.h" michael@0: #include "base/base_export.h" michael@0: #include "base/logging.h" michael@0: #include "base/memory/ref_counted.h" michael@0: #include "base/sequence_checker.h" michael@0: #include "base/template_util.h" michael@0: michael@0: namespace base { michael@0: michael@0: template class SupportsWeakPtr; michael@0: template class WeakPtr; michael@0: michael@0: namespace internal { michael@0: // These classes are part of the WeakPtr implementation. michael@0: // DO NOT USE THESE CLASSES DIRECTLY YOURSELF. michael@0: michael@0: class BASE_EXPORT WeakReference { michael@0: public: michael@0: // Although Flag is bound to a specific thread, it may be deleted from another michael@0: // via base::WeakPtr::~WeakPtr(). michael@0: class Flag : public RefCountedThreadSafe { michael@0: public: michael@0: Flag(); michael@0: michael@0: void Invalidate(); michael@0: bool IsValid() const; michael@0: michael@0: private: michael@0: friend class base::RefCountedThreadSafe; michael@0: michael@0: ~Flag(); michael@0: michael@0: SequenceChecker sequence_checker_; michael@0: bool is_valid_; michael@0: }; michael@0: michael@0: WeakReference(); michael@0: explicit WeakReference(const Flag* flag); michael@0: ~WeakReference(); michael@0: michael@0: bool is_valid() const; michael@0: michael@0: private: michael@0: scoped_refptr flag_; michael@0: }; michael@0: michael@0: class BASE_EXPORT WeakReferenceOwner { michael@0: public: michael@0: WeakReferenceOwner(); michael@0: ~WeakReferenceOwner(); michael@0: michael@0: WeakReference GetRef() const; michael@0: michael@0: bool HasRefs() const { michael@0: return flag_.get() && !flag_->HasOneRef(); michael@0: } michael@0: michael@0: void Invalidate(); michael@0: michael@0: private: michael@0: mutable scoped_refptr flag_; michael@0: }; michael@0: michael@0: // This class simplifies the implementation of WeakPtr's type conversion michael@0: // constructor by avoiding the need for a public accessor for ref_. A michael@0: // WeakPtr cannot access the private members of WeakPtr, so this michael@0: // base class gives us a way to access ref_ in a protected fashion. michael@0: class BASE_EXPORT WeakPtrBase { michael@0: public: michael@0: WeakPtrBase(); michael@0: ~WeakPtrBase(); michael@0: michael@0: protected: michael@0: explicit WeakPtrBase(const WeakReference& ref); michael@0: michael@0: WeakReference ref_; michael@0: }; michael@0: michael@0: // This class provides a common implementation of common functions that would michael@0: // otherwise get instantiated separately for each distinct instantiation of michael@0: // SupportsWeakPtr<>. michael@0: class SupportsWeakPtrBase { michael@0: public: michael@0: // A safe static downcast of a WeakPtr to WeakPtr. This michael@0: // conversion will only compile if there is exists a Base which inherits michael@0: // from SupportsWeakPtr. See base::AsWeakPtr() below for a helper michael@0: // function that makes calling this easier. michael@0: template michael@0: static WeakPtr StaticAsWeakPtr(Derived* t) { michael@0: typedef michael@0: is_convertible convertible; michael@0: COMPILE_ASSERT(convertible::value, michael@0: AsWeakPtr_argument_inherits_from_SupportsWeakPtr); michael@0: return AsWeakPtrImpl(t, *t); michael@0: } michael@0: michael@0: private: michael@0: // This template function uses type inference to find a Base of Derived michael@0: // which is an instance of SupportsWeakPtr. We can then safely michael@0: // static_cast the Base* to a Derived*. michael@0: template michael@0: static WeakPtr AsWeakPtrImpl( michael@0: Derived* t, const SupportsWeakPtr&) { michael@0: WeakPtr ptr = t->Base::AsWeakPtr(); michael@0: return WeakPtr(ptr.ref_, static_cast(ptr.ptr_)); michael@0: } michael@0: }; michael@0: michael@0: } // namespace internal michael@0: michael@0: template class WeakPtrFactory; michael@0: michael@0: // The WeakPtr class holds a weak reference to |T*|. michael@0: // michael@0: // This class is designed to be used like a normal pointer. You should always michael@0: // null-test an object of this class before using it or invoking a method that michael@0: // may result in the underlying object being destroyed. michael@0: // michael@0: // EXAMPLE: michael@0: // michael@0: // class Foo { ... }; michael@0: // WeakPtr foo; michael@0: // if (foo) michael@0: // foo->method(); michael@0: // michael@0: template michael@0: class WeakPtr : public internal::WeakPtrBase { michael@0: public: michael@0: WeakPtr() : ptr_(NULL) { michael@0: } michael@0: michael@0: // Allow conversion from U to T provided U "is a" T. Note that this michael@0: // is separate from the (implicit) copy constructor. michael@0: template michael@0: WeakPtr(const WeakPtr& other) : WeakPtrBase(other), ptr_(other.ptr_) { michael@0: } michael@0: michael@0: T* get() const { return ref_.is_valid() ? ptr_ : NULL; } michael@0: michael@0: T& operator*() const { michael@0: DCHECK(get() != NULL); michael@0: return *get(); michael@0: } michael@0: T* operator->() const { michael@0: DCHECK(get() != NULL); michael@0: return get(); michael@0: } michael@0: michael@0: // Allow WeakPtr to be used in boolean expressions, but not michael@0: // implicitly convertible to a real bool (which is dangerous). michael@0: // michael@0: // Note that this trick is only safe when the == and != operators michael@0: // are declared explicitly, as otherwise "weak_ptr1 == weak_ptr2" michael@0: // will compile but do the wrong thing (i.e., convert to Testable michael@0: // and then do the comparison). michael@0: private: michael@0: typedef T* WeakPtr::*Testable; michael@0: michael@0: public: michael@0: operator Testable() const { return get() ? &WeakPtr::ptr_ : NULL; } michael@0: michael@0: void reset() { michael@0: ref_ = internal::WeakReference(); michael@0: ptr_ = NULL; michael@0: } michael@0: michael@0: private: michael@0: // Explicitly declare comparison operators as required by the bool michael@0: // trick, but keep them private. michael@0: template bool operator==(WeakPtr const&) const; michael@0: template bool operator!=(WeakPtr const&) const; michael@0: michael@0: friend class internal::SupportsWeakPtrBase; michael@0: template friend class WeakPtr; michael@0: friend class SupportsWeakPtr; michael@0: friend class WeakPtrFactory; michael@0: michael@0: WeakPtr(const internal::WeakReference& ref, T* ptr) michael@0: : WeakPtrBase(ref), michael@0: ptr_(ptr) { michael@0: } michael@0: michael@0: // This pointer is only valid when ref_.is_valid() is true. Otherwise, its michael@0: // value is undefined (as opposed to NULL). michael@0: T* ptr_; michael@0: }; michael@0: michael@0: // A class may be composed of a WeakPtrFactory and thereby michael@0: // control how it exposes weak pointers to itself. This is helpful if you only michael@0: // need weak pointers within the implementation of a class. This class is also michael@0: // useful when working with primitive types. For example, you could have a michael@0: // WeakPtrFactory that is used to pass around a weak reference to a bool. michael@0: template michael@0: class WeakPtrFactory { michael@0: public: michael@0: explicit WeakPtrFactory(T* ptr) : ptr_(ptr) { michael@0: } michael@0: michael@0: ~WeakPtrFactory() { michael@0: ptr_ = NULL; michael@0: } michael@0: michael@0: WeakPtr GetWeakPtr() { michael@0: DCHECK(ptr_); michael@0: return WeakPtr(weak_reference_owner_.GetRef(), ptr_); michael@0: } michael@0: michael@0: // Call this method to invalidate all existing weak pointers. michael@0: void InvalidateWeakPtrs() { michael@0: DCHECK(ptr_); michael@0: weak_reference_owner_.Invalidate(); michael@0: } michael@0: michael@0: // Call this method to determine if any weak pointers exist. michael@0: bool HasWeakPtrs() const { michael@0: DCHECK(ptr_); michael@0: return weak_reference_owner_.HasRefs(); michael@0: } michael@0: michael@0: private: michael@0: internal::WeakReferenceOwner weak_reference_owner_; michael@0: T* ptr_; michael@0: DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory); michael@0: }; michael@0: michael@0: // A class may extend from SupportsWeakPtr to let others take weak pointers to michael@0: // it. This avoids the class itself implementing boilerplate to dispense weak michael@0: // pointers. However, since SupportsWeakPtr's destructor won't invalidate michael@0: // weak pointers to the class until after the derived class' members have been michael@0: // destroyed, its use can lead to subtle use-after-destroy issues. michael@0: template michael@0: class SupportsWeakPtr : public internal::SupportsWeakPtrBase { michael@0: public: michael@0: SupportsWeakPtr() {} michael@0: michael@0: WeakPtr AsWeakPtr() { michael@0: return WeakPtr(weak_reference_owner_.GetRef(), static_cast(this)); michael@0: } michael@0: michael@0: protected: michael@0: ~SupportsWeakPtr() {} michael@0: michael@0: private: michael@0: internal::WeakReferenceOwner weak_reference_owner_; michael@0: DISALLOW_COPY_AND_ASSIGN(SupportsWeakPtr); michael@0: }; michael@0: michael@0: // Helper function that uses type deduction to safely return a WeakPtr michael@0: // when Derived doesn't directly extend SupportsWeakPtr, instead it michael@0: // extends a Base that extends SupportsWeakPtr. michael@0: // michael@0: // EXAMPLE: michael@0: // class Base : public base::SupportsWeakPtr {}; michael@0: // class Derived : public Base {}; michael@0: // michael@0: // Derived derived; michael@0: // base::WeakPtr ptr = base::AsWeakPtr(&derived); michael@0: // michael@0: // Note that the following doesn't work (invalid type conversion) since michael@0: // Derived::AsWeakPtr() is WeakPtr SupportsWeakPtr::AsWeakPtr(), michael@0: // and there's no way to safely cast WeakPtr to WeakPtr at michael@0: // the caller. michael@0: // michael@0: // base::WeakPtr ptr = derived.AsWeakPtr(); // Fails. michael@0: michael@0: template michael@0: WeakPtr AsWeakPtr(Derived* t) { michael@0: return internal::SupportsWeakPtrBase::StaticAsWeakPtr(t); michael@0: } michael@0: michael@0: } // namespace base michael@0: michael@0: #endif // BASE_MEMORY_WEAK_PTR_H_