1 // Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012
2 // Google Inc. All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the name Chromium Embedded
15 // Framework nor the names of its contributors may be used to endorse
16 // or promote products derived from this software without specific prior
17 // written permission.
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 // Weak pointers are pointers to an object that do not affect its lifetime,
32 // and which may be invalidated (i.e. reset to NULL) by the object, or its
33 // owner, at any time, most commonly when the object is about to be deleted.
35 // Weak pointers are useful when an object needs to be accessed safely by one
36 // or more objects other than its owner, and those callers can cope with the
37 // object vanishing and e.g. tasks posted to it being silently dropped.
38 // Reference-counting such an object would complicate the ownership graph and
39 // make it harder to reason about the object's lifetime.
45 // void SpawnWorker() { Worker::StartNew(weak_factory_.GetWeakPtr()); }
46 // void WorkComplete(const Result& result) { ... }
48 // // Member variables should appear before the WeakPtrFactory, to ensure
49 // // that any WeakPtrs to Controller are invalidated before its members
50 // // variable's destructors are executed, rendering them invalid.
51 // WeakPtrFactory<Controller> weak_factory_;
56 // static void StartNew(const WeakPtr<Controller>& controller) {
57 // Worker* worker = new Worker(controller);
58 // // Kick off asynchronous processing...
61 // Worker(const WeakPtr<Controller>& controller)
62 // : controller_(controller) {}
63 // void DidCompleteAsynchronousProcessing(const Result& result) {
65 // controller_->WorkComplete(result);
67 // WeakPtr<Controller> controller_;
70 // With this implementation a caller may use SpawnWorker() to dispatch multiple
71 // Workers and subsequently delete the Controller, without waiting for all
72 // Workers to have completed.
74 // ------------------------- IMPORTANT: Thread-safety -------------------------
76 // Weak pointers may be passed safely between threads, but must always be
77 // dereferenced and invalidated on the same thread otherwise checking the
78 // pointer would be racey.
80 // To ensure correct use, the first time a WeakPtr issued by a WeakPtrFactory
81 // is dereferenced, the factory and its WeakPtrs become bound to the calling
82 // thread, and cannot be dereferenced or invalidated on any other thread. Bound
83 // WeakPtrs can still be handed off to other threads, e.g. to use to post tasks
84 // back to object on the bound thread.
86 // Invalidating the factory's WeakPtrs un-binds it from the thread, allowing it
87 // to be passed for a different thread to use or delete it.
89 #ifndef CEF_INCLUDE_BASE_CEF_WEAK_PTR_H_
90 #define CEF_INCLUDE_BASE_CEF_WEAK_PTR_H_
93 #if defined(BASE_MEMORY_WEAK_PTR_H_)
94 // Do nothing if the Chromium header has already been included.
95 // This can happen in cases where Chromium code is used directly by the
96 // client application. When using Chromium code directly always include
97 // the Chromium header first to avoid type conflicts.
98 #elif defined(BUILDING_CEF_SHARED)
99 // When building CEF include the Chromium header directly.
100 #include "base/memory/weak_ptr.h"
101 #else // !BUILDING_CEF_SHARED
102 // The following is substantially similar to the Chromium implementation.
103 // If the Chromium implementation diverges the below implementation should be
106 #include "include/base/cef_basictypes.h"
107 #include "include/base/cef_logging.h"
108 #include "include/base/cef_ref_counted.h"
109 #include "include/base/cef_template_util.h"
110 #include "include/base/cef_thread_checker.h"
114 template <typename T> class SupportsWeakPtr;
115 template <typename T> class WeakPtr;
117 namespace cef_internal {
118 // These classes are part of the WeakPtr implementation.
119 // DO NOT USE THESE CLASSES DIRECTLY YOURSELF.
121 class WeakReference {
123 // Although Flag is bound to a specific thread, it may be deleted from another
124 // via base::WeakPtr::~WeakPtr().
125 class Flag : public RefCountedThreadSafe<Flag> {
130 bool IsValid() const;
133 friend class base::RefCountedThreadSafe<Flag>;
137 // The current Chromium implementation uses SequenceChecker instead of
138 // ThreadChecker to support SequencedWorkerPools. CEF does not yet expose
139 // the concept of SequencedWorkerPools.
140 ThreadChecker thread_checker_;
145 explicit WeakReference(const Flag* flag);
148 bool is_valid() const;
151 scoped_refptr<const Flag> flag_;
154 class WeakReferenceOwner {
156 WeakReferenceOwner();
157 ~WeakReferenceOwner();
159 WeakReference GetRef() const;
161 bool HasRefs() const {
162 return flag_.get() && !flag_->HasOneRef();
168 mutable scoped_refptr<WeakReference::Flag> flag_;
171 // This class simplifies the implementation of WeakPtr's type conversion
172 // constructor by avoiding the need for a public accessor for ref_. A
173 // WeakPtr<T> cannot access the private members of WeakPtr<U>, so this
174 // base class gives us a way to access ref_ in a protected fashion.
181 explicit WeakPtrBase(const WeakReference& ref);
186 // This class provides a common implementation of common functions that would
187 // otherwise get instantiated separately for each distinct instantiation of
188 // SupportsWeakPtr<>.
189 class SupportsWeakPtrBase {
191 // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This
192 // conversion will only compile if there is exists a Base which inherits
193 // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper
194 // function that makes calling this easier.
195 template<typename Derived>
196 static WeakPtr<Derived> StaticAsWeakPtr(Derived* t) {
198 is_convertible<Derived, cef_internal::SupportsWeakPtrBase&> convertible;
199 COMPILE_ASSERT(convertible::value,
200 AsWeakPtr_argument_inherits_from_SupportsWeakPtr);
201 return AsWeakPtrImpl<Derived>(t, *t);
205 // This template function uses type inference to find a Base of Derived
206 // which is an instance of SupportsWeakPtr<Base>. We can then safely
207 // static_cast the Base* to a Derived*.
208 template <typename Derived, typename Base>
209 static WeakPtr<Derived> AsWeakPtrImpl(
210 Derived* t, const SupportsWeakPtr<Base>&) {
211 WeakPtr<Base> ptr = t->Base::AsWeakPtr();
212 return WeakPtr<Derived>(ptr.ref_, static_cast<Derived*>(ptr.ptr_));
216 } // namespace cef_internal
218 template <typename T> class WeakPtrFactory;
220 // The WeakPtr class holds a weak reference to |T*|.
222 // This class is designed to be used like a normal pointer. You should always
223 // null-test an object of this class before using it or invoking a method that
224 // may result in the underlying object being destroyed.
228 // class Foo { ... };
233 template <typename T>
234 class WeakPtr : public cef_internal::WeakPtrBase {
236 WeakPtr() : ptr_(NULL) {
239 // Allow conversion from U to T provided U "is a" T. Note that this
240 // is separate from the (implicit) copy constructor.
241 template <typename U>
242 WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other), ptr_(other.ptr_) {
245 T* get() const { return ref_.is_valid() ? ptr_ : NULL; }
247 T& operator*() const {
248 DCHECK(get() != NULL);
251 T* operator->() const {
252 DCHECK(get() != NULL);
256 // Allow WeakPtr<element_type> to be used in boolean expressions, but not
257 // implicitly convertible to a real bool (which is dangerous).
259 // Note that this trick is only safe when the == and != operators
260 // are declared explicitly, as otherwise "weak_ptr1 == weak_ptr2"
261 // will compile but do the wrong thing (i.e., convert to Testable
262 // and then do the comparison).
264 typedef T* WeakPtr::*Testable;
267 operator Testable() const { return get() ? &WeakPtr::ptr_ : NULL; }
270 ref_ = cef_internal::WeakReference();
275 // Explicitly declare comparison operators as required by the bool
276 // trick, but keep them private.
277 template <class U> bool operator==(WeakPtr<U> const&) const;
278 template <class U> bool operator!=(WeakPtr<U> const&) const;
280 friend class cef_internal::SupportsWeakPtrBase;
281 template <typename U> friend class WeakPtr;
282 friend class SupportsWeakPtr<T>;
283 friend class WeakPtrFactory<T>;
285 WeakPtr(const cef_internal::WeakReference& ref, T* ptr)
290 // This pointer is only valid when ref_.is_valid() is true. Otherwise, its
291 // value is undefined (as opposed to NULL).
295 // A class may be composed of a WeakPtrFactory and thereby
296 // control how it exposes weak pointers to itself. This is helpful if you only
297 // need weak pointers within the implementation of a class. This class is also
298 // useful when working with primitive types. For example, you could have a
299 // WeakPtrFactory<bool> that is used to pass around a weak reference to a bool.
301 class WeakPtrFactory {
303 explicit WeakPtrFactory(T* ptr) : ptr_(ptr) {
310 WeakPtr<T> GetWeakPtr() {
312 return WeakPtr<T>(weak_reference_owner_.GetRef(), ptr_);
315 // Call this method to invalidate all existing weak pointers.
316 void InvalidateWeakPtrs() {
318 weak_reference_owner_.Invalidate();
321 // Call this method to determine if any weak pointers exist.
322 bool HasWeakPtrs() const {
324 return weak_reference_owner_.HasRefs();
328 cef_internal::WeakReferenceOwner weak_reference_owner_;
330 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory);
333 // A class may extend from SupportsWeakPtr to let others take weak pointers to
334 // it. This avoids the class itself implementing boilerplate to dispense weak
335 // pointers. However, since SupportsWeakPtr's destructor won't invalidate
336 // weak pointers to the class until after the derived class' members have been
337 // destroyed, its use can lead to subtle use-after-destroy issues.
339 class SupportsWeakPtr : public cef_internal::SupportsWeakPtrBase {
343 WeakPtr<T> AsWeakPtr() {
344 return WeakPtr<T>(weak_reference_owner_.GetRef(), static_cast<T*>(this));
348 ~SupportsWeakPtr() {}
351 cef_internal::WeakReferenceOwner weak_reference_owner_;
352 DISALLOW_COPY_AND_ASSIGN(SupportsWeakPtr);
355 // Helper function that uses type deduction to safely return a WeakPtr<Derived>
356 // when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it
357 // extends a Base that extends SupportsWeakPtr<Base>.
360 // class Base : public base::SupportsWeakPtr<Producer> {};
361 // class Derived : public Base {};
364 // base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived);
366 // Note that the following doesn't work (invalid type conversion) since
367 // Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(),
368 // and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at
371 // base::WeakPtr<Derived> ptr = derived.AsWeakPtr(); // Fails.
373 template <typename Derived>
374 WeakPtr<Derived> AsWeakPtr(Derived* t) {
375 return cef_internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t);
380 #endif // !BUILDING_CEF_SHARED
382 #endif // CEF_INCLUDE_BASE_CEF_WEAK_PTR_H_