blob: 67b6ec154223bd593ef10616ad3cdfa871921ba9 [file] [log] [blame]
perkj8ff860a2016-10-03 07:30:041/*
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 Bonadei92ea95e2017-09-15 04:47:3111#ifndef RTC_BASE_WEAK_PTR_H_
12#define RTC_BASE_WEAK_PTR_H_
perkj8ff860a2016-10-03 07:30:0413
Henrik Kjellanderec78f1c2017-06-29 05:52:5014#include <memory>
Henrik Kjellanderec78f1c2017-06-29 05:52:5015#include <utility>
16
Mirko Bonadeid9708072019-01-25 19:26:4817#include "api/scoped_refptr.h"
Artem Titovd15a5752021-02-10 13:31:2418#include "api/sequence_checker.h"
Tommiaf3dfd82024-04-24 08:54:1919#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 17:11:0020#include "rtc_base/ref_count.h"
21#include "rtc_base/ref_counted_object.h"
Mirko Bonadei20e4c802020-11-23 10:07:4222#include "rtc_base/system/no_unique_address.h"
Tommiaf3dfd82024-04-24 08:54:1923#include "rtc_base/thread_annotations.h"
Henrik Kjellanderec78f1c2017-06-29 05:52:5024
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
89namespace rtc {
90
91namespace internal {
92
93class WeakReference {
94 public:
95 // Although Flag is bound to a specific sequence, it may be
96 // deleted from another via base::WeakPtr::~WeakPtr().
Tommiaf3dfd82024-04-24 08:54:1997 class Flag {
Henrik Kjellanderec78f1c2017-06-29 05:52:5098 public:
Tommiaf3dfd82024-04-24 08:54:1999 Flag() = default;
Henrik Kjellanderec78f1c2017-06-29 05:52:50100
101 void Invalidate();
102 bool IsValid() const;
103
104 private:
Tommiaf3dfd82024-04-24 08:54:19105 friend class FinalRefCountedObject<Flag>;
Henrik Kjellanderec78f1c2017-06-29 05:52:50106
Tommiaf3dfd82024-04-24 08:54:19107 ~Flag() = default;
Henrik Kjellanderec78f1c2017-06-29 05:52:50108
Tommic8482682023-03-23 21:20:39109 RTC_NO_UNIQUE_ADDRESS ::webrtc::SequenceChecker checker_{
110 webrtc::SequenceChecker::kDetached};
Tommiaf3dfd82024-04-24 08:54:19111 bool is_valid_ RTC_GUARDED_BY(checker_) = true;
Henrik Kjellanderec78f1c2017-06-29 05:52:50112 };
113
Tommiaf3dfd82024-04-24 08:54:19114 // `RefCountedFlag` is the reference counted (shared), non-virtual, flag type.
115 using RefCountedFlag = FinalRefCountedObject<Flag>;
116
Henrik Kjellanderec78f1c2017-06-29 05:52:50117 WeakReference();
Tommiaf3dfd82024-04-24 08:54:19118 explicit WeakReference(const RefCountedFlag* flag);
Henrik Kjellanderec78f1c2017-06-29 05:52:50119 ~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:
Tommiaf3dfd82024-04-24 08:54:19129 scoped_refptr<const RefCountedFlag> flag_;
Henrik Kjellanderec78f1c2017-06-29 05:52:50130};
131
132class 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:
Tommiaf3dfd82024-04-24 08:54:19144 mutable scoped_refptr<WeakReference::RefCountedFlag> flag_;
Henrik Kjellanderec78f1c2017-06-29 05:52:50145};
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.
151class 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
169template <typename T>
170class WeakPtrFactory;
171
172template <typename T>
173class 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.
219template <class T>
220bool operator!=(const WeakPtr<T>& weak_ptr, std::nullptr_t) {
221 return !(weak_ptr == nullptr);
222}
223template <class T>
224bool operator!=(std::nullptr_t, const WeakPtr<T>& weak_ptr) {
225 return weak_ptr != nullptr;
226}
227template <class T>
228bool operator==(const WeakPtr<T>& weak_ptr, std::nullptr_t) {
229 return weak_ptr.get() == nullptr;
230}
231template <class T>
232bool 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()).
246template <class T>
247class WeakPtrFactory {
248 public:
249 explicit WeakPtrFactory(T* ptr) : ptr_(ptr) {}
250
Niels Möllerde953292020-09-29 07:46:21251 WeakPtrFactory() = delete;
252 WeakPtrFactory(const WeakPtrFactory&) = delete;
253 WeakPtrFactory& operator=(const WeakPtrFactory&) = delete;
254
Henrik Kjellanderec78f1c2017-06-29 05:52:50255 ~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 Kjellanderec78f1c2017-06-29 05:52:50277};
278
279} // namespace rtc
perkj8ff860a2016-10-03 07:30:04280
Mirko Bonadei92ea95e2017-09-15 04:47:31281#endif // RTC_BASE_WEAK_PTR_H_