perkj | 8ff860a | 2016-10-03 07:30:04 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2016 The WebRTC Project Authors. All rights reserved. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license |
| 5 | * that can be found in the LICENSE file in the root of the source |
| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 | |
Mirko Bonadei | 92ea95e | 2017-09-15 04:47:31 | [diff] [blame] | 11 | #ifndef RTC_BASE_WEAK_PTR_H_ |
| 12 | #define RTC_BASE_WEAK_PTR_H_ |
perkj | 8ff860a | 2016-10-03 07:30:04 | [diff] [blame] | 13 | |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 14 | #include <memory> |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 15 | #include <utility> |
| 16 | |
Mirko Bonadei | d970807 | 2019-01-25 19:26:48 | [diff] [blame] | 17 | #include "api/scoped_refptr.h" |
Artem Titov | d15a575 | 2021-02-10 13:31:24 | [diff] [blame] | 18 | #include "api/sequence_checker.h" |
Tommi | af3dfd8 | 2024-04-24 08:54:19 | [diff] [blame] | 19 | #include "rtc_base/checks.h" |
Steve Anton | 10542f2 | 2019-01-11 17:11:00 | [diff] [blame] | 20 | #include "rtc_base/ref_count.h" |
| 21 | #include "rtc_base/ref_counted_object.h" |
Mirko Bonadei | 20e4c80 | 2020-11-23 10:07:42 | [diff] [blame] | 22 | #include "rtc_base/system/no_unique_address.h" |
Tommi | af3dfd8 | 2024-04-24 08:54:19 | [diff] [blame] | 23 | #include "rtc_base/thread_annotations.h" |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 24 | |
| 25 | // The implementation is borrowed from chromium except that it does not |
| 26 | // implement SupportsWeakPtr. |
| 27 | |
| 28 | // Weak pointers are pointers to an object that do not affect its lifetime, |
| 29 | // and which may be invalidated (i.e. reset to nullptr) by the object, or its |
| 30 | // owner, at any time, most commonly when the object is about to be deleted. |
| 31 | |
| 32 | // Weak pointers are useful when an object needs to be accessed safely by one |
| 33 | // or more objects other than its owner, and those callers can cope with the |
| 34 | // object vanishing and e.g. tasks posted to it being silently dropped. |
| 35 | // Reference-counting such an object would complicate the ownership graph and |
| 36 | // make it harder to reason about the object's lifetime. |
| 37 | |
| 38 | // EXAMPLE: |
| 39 | // |
| 40 | // class Controller { |
| 41 | // public: |
| 42 | // Controller() : weak_factory_(this) {} |
| 43 | // void SpawnWorker() { Worker::StartNew(weak_factory_.GetWeakPtr()); } |
| 44 | // void WorkComplete(const Result& result) { ... } |
| 45 | // private: |
| 46 | // // Member variables should appear before the WeakPtrFactory, to ensure |
| 47 | // // that any WeakPtrs to Controller are invalidated before its members |
| 48 | // // variable's destructors are executed, rendering them invalid. |
| 49 | // WeakPtrFactory<Controller> weak_factory_; |
| 50 | // }; |
| 51 | // |
| 52 | // class Worker { |
| 53 | // public: |
| 54 | // static void StartNew(const WeakPtr<Controller>& controller) { |
| 55 | // Worker* worker = new Worker(controller); |
| 56 | // // Kick off asynchronous processing... |
| 57 | // } |
| 58 | // private: |
| 59 | // Worker(const WeakPtr<Controller>& controller) |
| 60 | // : controller_(controller) {} |
| 61 | // void DidCompleteAsynchronousProcessing(const Result& result) { |
| 62 | // if (controller_) |
| 63 | // controller_->WorkComplete(result); |
| 64 | // } |
| 65 | // WeakPtr<Controller> controller_; |
| 66 | // }; |
| 67 | // |
| 68 | // With this implementation a caller may use SpawnWorker() to dispatch multiple |
| 69 | // Workers and subsequently delete the Controller, without waiting for all |
| 70 | // Workers to have completed. |
| 71 | |
| 72 | // ------------------------- IMPORTANT: Thread-safety ------------------------- |
| 73 | |
| 74 | // Weak pointers may be passed safely between threads, but must always be |
| 75 | // dereferenced and invalidated on the same TaskQueue or thread, otherwise |
| 76 | // checking the pointer would be racey. |
| 77 | // |
| 78 | // To ensure correct use, the first time a WeakPtr issued by a WeakPtrFactory |
| 79 | // is dereferenced, the factory and its WeakPtrs become bound to the calling |
| 80 | // TaskQueue/thread, and cannot be dereferenced or |
| 81 | // invalidated on any other TaskQueue/thread. Bound WeakPtrs can still be handed |
| 82 | // off to other TaskQueues, e.g. to use to post tasks back to object on the |
| 83 | // bound sequence. |
| 84 | // |
| 85 | // Thus, at least one WeakPtr object must exist and have been dereferenced on |
| 86 | // the correct thread to enforce that other WeakPtr objects will enforce they |
| 87 | // are used on the desired thread. |
| 88 | |
| 89 | namespace rtc { |
| 90 | |
| 91 | namespace internal { |
| 92 | |
| 93 | class WeakReference { |
| 94 | public: |
| 95 | // Although Flag is bound to a specific sequence, it may be |
| 96 | // deleted from another via base::WeakPtr::~WeakPtr(). |
Tommi | af3dfd8 | 2024-04-24 08:54:19 | [diff] [blame] | 97 | class Flag { |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 98 | public: |
Tommi | af3dfd8 | 2024-04-24 08:54:19 | [diff] [blame] | 99 | Flag() = default; |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 100 | |
| 101 | void Invalidate(); |
| 102 | bool IsValid() const; |
| 103 | |
| 104 | private: |
Tommi | af3dfd8 | 2024-04-24 08:54:19 | [diff] [blame] | 105 | friend class FinalRefCountedObject<Flag>; |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 106 | |
Tommi | af3dfd8 | 2024-04-24 08:54:19 | [diff] [blame] | 107 | ~Flag() = default; |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 108 | |
Tommi | c848268 | 2023-03-23 21:20:39 | [diff] [blame] | 109 | RTC_NO_UNIQUE_ADDRESS ::webrtc::SequenceChecker checker_{ |
| 110 | webrtc::SequenceChecker::kDetached}; |
Tommi | af3dfd8 | 2024-04-24 08:54:19 | [diff] [blame] | 111 | bool is_valid_ RTC_GUARDED_BY(checker_) = true; |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 112 | }; |
| 113 | |
Tommi | af3dfd8 | 2024-04-24 08:54:19 | [diff] [blame] | 114 | // `RefCountedFlag` is the reference counted (shared), non-virtual, flag type. |
| 115 | using RefCountedFlag = FinalRefCountedObject<Flag>; |
| 116 | |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 117 | WeakReference(); |
Tommi | af3dfd8 | 2024-04-24 08:54:19 | [diff] [blame] | 118 | explicit WeakReference(const RefCountedFlag* flag); |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 119 | ~WeakReference(); |
| 120 | |
| 121 | WeakReference(WeakReference&& other); |
| 122 | WeakReference(const WeakReference& other); |
| 123 | WeakReference& operator=(WeakReference&& other) = default; |
| 124 | WeakReference& operator=(const WeakReference& other) = default; |
| 125 | |
| 126 | bool is_valid() const; |
| 127 | |
| 128 | private: |
Tommi | af3dfd8 | 2024-04-24 08:54:19 | [diff] [blame] | 129 | scoped_refptr<const RefCountedFlag> flag_; |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 130 | }; |
| 131 | |
| 132 | class WeakReferenceOwner { |
| 133 | public: |
| 134 | WeakReferenceOwner(); |
| 135 | ~WeakReferenceOwner(); |
| 136 | |
| 137 | WeakReference GetRef() const; |
| 138 | |
| 139 | bool HasRefs() const { return flag_.get() && !flag_->HasOneRef(); } |
| 140 | |
| 141 | void Invalidate(); |
| 142 | |
| 143 | private: |
Tommi | af3dfd8 | 2024-04-24 08:54:19 | [diff] [blame] | 144 | mutable scoped_refptr<WeakReference::RefCountedFlag> flag_; |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 145 | }; |
| 146 | |
| 147 | // This class simplifies the implementation of WeakPtr's type conversion |
| 148 | // constructor by avoiding the need for a public accessor for ref_. A |
| 149 | // WeakPtr<T> cannot access the private members of WeakPtr<U>, so this |
| 150 | // base class gives us a way to access ref_ in a protected fashion. |
| 151 | class WeakPtrBase { |
| 152 | public: |
| 153 | WeakPtrBase(); |
| 154 | ~WeakPtrBase(); |
| 155 | |
| 156 | WeakPtrBase(const WeakPtrBase& other) = default; |
| 157 | WeakPtrBase(WeakPtrBase&& other) = default; |
| 158 | WeakPtrBase& operator=(const WeakPtrBase& other) = default; |
| 159 | WeakPtrBase& operator=(WeakPtrBase&& other) = default; |
| 160 | |
| 161 | protected: |
| 162 | explicit WeakPtrBase(const WeakReference& ref); |
| 163 | |
| 164 | WeakReference ref_; |
| 165 | }; |
| 166 | |
| 167 | } // namespace internal |
| 168 | |
| 169 | template <typename T> |
| 170 | class WeakPtrFactory; |
| 171 | |
| 172 | template <typename T> |
| 173 | class WeakPtr : public internal::WeakPtrBase { |
| 174 | public: |
| 175 | WeakPtr() : ptr_(nullptr) {} |
| 176 | |
| 177 | // Allow conversion from U to T provided U "is a" T. Note that this |
| 178 | // is separate from the (implicit) copy and move constructors. |
| 179 | template <typename U> |
| 180 | WeakPtr(const WeakPtr<U>& other) |
| 181 | : internal::WeakPtrBase(other), ptr_(other.ptr_) {} |
| 182 | template <typename U> |
| 183 | WeakPtr(WeakPtr<U>&& other) |
| 184 | : internal::WeakPtrBase(std::move(other)), ptr_(other.ptr_) {} |
| 185 | |
| 186 | T* get() const { return ref_.is_valid() ? ptr_ : nullptr; } |
| 187 | |
| 188 | T& operator*() const { |
| 189 | RTC_DCHECK(get() != nullptr); |
| 190 | return *get(); |
| 191 | } |
| 192 | T* operator->() const { |
| 193 | RTC_DCHECK(get() != nullptr); |
| 194 | return get(); |
| 195 | } |
| 196 | |
| 197 | void reset() { |
| 198 | ref_ = internal::WeakReference(); |
| 199 | ptr_ = nullptr; |
| 200 | } |
| 201 | |
| 202 | // Allow conditionals to test validity, e.g. if (weak_ptr) {...}; |
| 203 | explicit operator bool() const { return get() != nullptr; } |
| 204 | |
| 205 | private: |
| 206 | template <typename U> |
| 207 | friend class WeakPtr; |
| 208 | friend class WeakPtrFactory<T>; |
| 209 | |
| 210 | WeakPtr(const internal::WeakReference& ref, T* ptr) |
| 211 | : internal::WeakPtrBase(ref), ptr_(ptr) {} |
| 212 | |
| 213 | // This pointer is only valid when ref_.is_valid() is true. Otherwise, its |
| 214 | // value is undefined (as opposed to nullptr). |
| 215 | T* ptr_; |
| 216 | }; |
| 217 | |
| 218 | // Allow callers to compare WeakPtrs against nullptr to test validity. |
| 219 | template <class T> |
| 220 | bool operator!=(const WeakPtr<T>& weak_ptr, std::nullptr_t) { |
| 221 | return !(weak_ptr == nullptr); |
| 222 | } |
| 223 | template <class T> |
| 224 | bool operator!=(std::nullptr_t, const WeakPtr<T>& weak_ptr) { |
| 225 | return weak_ptr != nullptr; |
| 226 | } |
| 227 | template <class T> |
| 228 | bool operator==(const WeakPtr<T>& weak_ptr, std::nullptr_t) { |
| 229 | return weak_ptr.get() == nullptr; |
| 230 | } |
| 231 | template <class T> |
| 232 | bool operator==(std::nullptr_t, const WeakPtr<T>& weak_ptr) { |
| 233 | return weak_ptr == nullptr; |
| 234 | } |
| 235 | |
| 236 | // A class may be composed of a WeakPtrFactory and thereby |
| 237 | // control how it exposes weak pointers to itself. This is helpful if you only |
| 238 | // need weak pointers within the implementation of a class. This class is also |
| 239 | // useful when working with primitive types. For example, you could have a |
| 240 | // WeakPtrFactory<bool> that is used to pass around a weak reference to a bool. |
| 241 | |
| 242 | // Note that GetWeakPtr must be called on one and only one TaskQueue or thread |
| 243 | // and the WeakPtr must only be dereferenced and invalidated on that same |
| 244 | // TaskQueue/thread. A WeakPtr instance can be copied and posted to other |
| 245 | // sequences though as long as it is not dereferenced (WeakPtr<T>::get()). |
| 246 | template <class T> |
| 247 | class WeakPtrFactory { |
| 248 | public: |
| 249 | explicit WeakPtrFactory(T* ptr) : ptr_(ptr) {} |
| 250 | |
Niels Möller | de95329 | 2020-09-29 07:46:21 | [diff] [blame] | 251 | WeakPtrFactory() = delete; |
| 252 | WeakPtrFactory(const WeakPtrFactory&) = delete; |
| 253 | WeakPtrFactory& operator=(const WeakPtrFactory&) = delete; |
| 254 | |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 255 | ~WeakPtrFactory() { ptr_ = nullptr; } |
| 256 | |
| 257 | WeakPtr<T> GetWeakPtr() { |
| 258 | RTC_DCHECK(ptr_); |
| 259 | return WeakPtr<T>(weak_reference_owner_.GetRef(), ptr_); |
| 260 | } |
| 261 | |
| 262 | // Call this method to invalidate all existing weak pointers. |
| 263 | void InvalidateWeakPtrs() { |
| 264 | RTC_DCHECK(ptr_); |
| 265 | weak_reference_owner_.Invalidate(); |
| 266 | } |
| 267 | |
| 268 | // Call this method to determine if any weak pointers exist. |
| 269 | bool HasWeakPtrs() const { |
| 270 | RTC_DCHECK(ptr_); |
| 271 | return weak_reference_owner_.HasRefs(); |
| 272 | } |
| 273 | |
| 274 | private: |
| 275 | internal::WeakReferenceOwner weak_reference_owner_; |
| 276 | T* ptr_; |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 277 | }; |
| 278 | |
| 279 | } // namespace rtc |
perkj | 8ff860a | 2016-10-03 07:30:04 | [diff] [blame] | 280 | |
Mirko Bonadei | 92ea95e | 2017-09-15 04:47:31 | [diff] [blame] | 281 | #endif // RTC_BASE_WEAK_PTR_H_ |