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