1 // Copyright 2017 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef BASE_MEMORY_SCOPED_REFPTR_H_
6 #define BASE_MEMORY_SCOPED_REFPTR_H_
7
8 #include <stddef.h>
9
10 #include <iosfwd>
11 #include <type_traits>
12 #include <utility>
13
14 #include "base/compiler_specific.h"
15 #include "base/logging.h"
16
17 template <class T>
18 class scoped_refptr;
19
20 namespace base {
21
22 template <class, typename>
23 class RefCounted;
24 template <class, typename>
25 class RefCountedThreadSafe;
26
27 template <typename T>
28 scoped_refptr<T> AdoptRef(T* t);
29
30 namespace subtle {
31
32 enum AdoptRefTag { kAdoptRefTag };
33 enum StartRefCountFromZeroTag { kStartRefCountFromZeroTag };
34 enum StartRefCountFromOneTag { kStartRefCountFromOneTag };
35
36 template <typename T, typename U, typename V>
IsRefCountPreferenceOverridden(const T *,const RefCounted<U,V> *)37 constexpr bool IsRefCountPreferenceOverridden(const T*,
38 const RefCounted<U, V>*) {
39 return !std::is_same<std::decay_t<decltype(T::kRefCountPreference)>,
40 std::decay_t<decltype(U::kRefCountPreference)>>::value;
41 }
42
43 template <typename T, typename U, typename V>
IsRefCountPreferenceOverridden(const T *,const RefCountedThreadSafe<U,V> *)44 constexpr bool IsRefCountPreferenceOverridden(
45 const T*,
46 const RefCountedThreadSafe<U, V>*) {
47 return !std::is_same<std::decay_t<decltype(T::kRefCountPreference)>,
48 std::decay_t<decltype(U::kRefCountPreference)>>::value;
49 }
50
IsRefCountPreferenceOverridden(...)51 constexpr bool IsRefCountPreferenceOverridden(...) {
52 return false;
53 }
54
55 } // namespace subtle
56
57 // Creates a scoped_refptr from a raw pointer without incrementing the reference
58 // count. Use this only for a newly created object whose reference count starts
59 // from 1 instead of 0.
60 template <typename T>
AdoptRef(T * obj)61 scoped_refptr<T> AdoptRef(T* obj) {
62 using Tag = std::decay_t<decltype(T::kRefCountPreference)>;
63 static_assert(std::is_same<subtle::StartRefCountFromOneTag, Tag>::value,
64 "Use AdoptRef only for the reference count starts from one.");
65
66 DCHECK(obj);
67 DCHECK(obj->HasOneRef());
68 obj->Adopted();
69 return scoped_refptr<T>(obj, subtle::kAdoptRefTag);
70 }
71
72 namespace subtle {
73
74 template <typename T>
AdoptRefIfNeeded(T * obj,StartRefCountFromZeroTag)75 scoped_refptr<T> AdoptRefIfNeeded(T* obj, StartRefCountFromZeroTag) {
76 return scoped_refptr<T>(obj);
77 }
78
79 template <typename T>
AdoptRefIfNeeded(T * obj,StartRefCountFromOneTag)80 scoped_refptr<T> AdoptRefIfNeeded(T* obj, StartRefCountFromOneTag) {
81 return AdoptRef(obj);
82 }
83
84 } // namespace subtle
85
86 // Constructs an instance of T, which is a ref counted type, and wraps the
87 // object into a scoped_refptr<T>.
88 template <typename T, typename... Args>
MakeRefCounted(Args &&...args)89 scoped_refptr<T> MakeRefCounted(Args&&... args) {
90 T* obj = new T(std::forward<Args>(args)...);
91 return subtle::AdoptRefIfNeeded(obj, T::kRefCountPreference);
92 }
93
94 // Takes an instance of T, which is a ref counted type, and wraps the object
95 // into a scoped_refptr<T>.
96 template <typename T>
WrapRefCounted(T * t)97 scoped_refptr<T> WrapRefCounted(T* t) {
98 return scoped_refptr<T>(t);
99 }
100
101 } // namespace base
102
103 //
104 // A smart pointer class for reference counted objects. Use this class instead
105 // of calling AddRef and Release manually on a reference counted object to
106 // avoid common memory leaks caused by forgetting to Release an object
107 // reference. Sample usage:
108 //
109 // class MyFoo : public RefCounted<MyFoo> {
110 // ...
111 // private:
112 // friend class RefCounted<MyFoo>; // Allow destruction by RefCounted<>.
113 // ~MyFoo(); // Destructor must be private/protected.
114 // };
115 //
116 // void some_function() {
117 // scoped_refptr<MyFoo> foo = MakeRefCounted<MyFoo>();
118 // foo->Method(param);
119 // // |foo| is released when this function returns
120 // }
121 //
122 // void some_other_function() {
123 // scoped_refptr<MyFoo> foo = MakeRefCounted<MyFoo>();
124 // ...
125 // foo = nullptr; // explicitly releases |foo|
126 // ...
127 // if (foo)
128 // foo->Method(param);
129 // }
130 //
131 // The above examples show how scoped_refptr<T> acts like a pointer to T.
132 // Given two scoped_refptr<T> classes, it is also possible to exchange
133 // references between the two objects, like so:
134 //
135 // {
136 // scoped_refptr<MyFoo> a = MakeRefCounted<MyFoo>();
137 // scoped_refptr<MyFoo> b;
138 //
139 // b.swap(a);
140 // // now, |b| references the MyFoo object, and |a| references nullptr.
141 // }
142 //
143 // To make both |a| and |b| in the above example reference the same MyFoo
144 // object, simply use the assignment operator:
145 //
146 // {
147 // scoped_refptr<MyFoo> a = MakeRefCounted<MyFoo>();
148 // scoped_refptr<MyFoo> b;
149 //
150 // b = a;
151 // // now, |a| and |b| each own a reference to the same MyFoo object.
152 // }
153 //
154 // Also see Chromium's ownership and calling conventions:
155 // https://chromium.googlesource.com/chromium/src/+/lkgr/styleguide/c++/c++.md#object-ownership-and-calling-conventions
156 // Specifically:
157 // If the function (at least sometimes) takes a ref on a refcounted object,
158 // declare the param as scoped_refptr<T>. The caller can decide whether it
159 // wishes to transfer ownership (by calling std::move(t) when passing t) or
160 // retain its ref (by simply passing t directly).
161 // In other words, use scoped_refptr like you would a std::unique_ptr except
162 // in the odd case where it's required to hold on to a ref while handing one
163 // to another component (if a component merely needs to use t on the stack
164 // without keeping a ref: pass t as a raw T*).
165 template <class T>
166 class scoped_refptr {
167 public:
168 typedef T element_type;
169
170 constexpr scoped_refptr() = default;
171
172 // Constructs from raw pointer. constexpr if |p| is null.
scoped_refptr(T * p)173 constexpr scoped_refptr(T* p) : ptr_(p) {
174 if (ptr_)
175 AddRef(ptr_);
176 }
177
178 // Copy constructor. This is required in addition to the copy conversion
179 // constructor below.
scoped_refptr(const scoped_refptr & r)180 scoped_refptr(const scoped_refptr& r) : scoped_refptr(r.ptr_) {}
181
182 // Copy conversion constructor.
183 template <typename U,
184 typename = typename std::enable_if<
185 std::is_convertible<U*, T*>::value>::type>
scoped_refptr(const scoped_refptr<U> & r)186 scoped_refptr(const scoped_refptr<U>& r) : scoped_refptr(r.ptr_) {}
187
188 // Move constructor. This is required in addition to the move conversion
189 // constructor below.
scoped_refptr(scoped_refptr && r)190 scoped_refptr(scoped_refptr&& r) noexcept : ptr_(r.ptr_) { r.ptr_ = nullptr; }
191
192 // Move conversion constructor.
193 template <typename U,
194 typename = typename std::enable_if<
195 std::is_convertible<U*, T*>::value>::type>
scoped_refptr(scoped_refptr<U> && r)196 scoped_refptr(scoped_refptr<U>&& r) noexcept : ptr_(r.ptr_) {
197 r.ptr_ = nullptr;
198 }
199
~scoped_refptr()200 ~scoped_refptr() {
201 static_assert(!base::subtle::IsRefCountPreferenceOverridden(
202 static_cast<T*>(nullptr), static_cast<T*>(nullptr)),
203 "It's unsafe to override the ref count preference."
204 " Please remove REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE"
205 " from subclasses.");
206 if (ptr_)
207 Release(ptr_);
208 }
209
get()210 T* get() const { return ptr_; }
211
212 T& operator*() const {
213 DCHECK(ptr_);
214 return *ptr_;
215 }
216
217 T* operator->() const {
218 DCHECK(ptr_);
219 return ptr_;
220 }
221
222 scoped_refptr& operator=(T* p) { return *this = scoped_refptr(p); }
223
224 // Unified assignment operator.
225 scoped_refptr& operator=(scoped_refptr r) noexcept {
226 swap(r);
227 return *this;
228 }
229
swap(scoped_refptr & r)230 void swap(scoped_refptr& r) noexcept { std::swap(ptr_, r.ptr_); }
231
232 explicit operator bool() const { return ptr_ != nullptr; }
233
234 template <typename U>
235 bool operator==(const scoped_refptr<U>& rhs) const {
236 return ptr_ == rhs.get();
237 }
238
239 template <typename U>
240 bool operator!=(const scoped_refptr<U>& rhs) const {
241 return !operator==(rhs);
242 }
243
244 template <typename U>
245 bool operator<(const scoped_refptr<U>& rhs) const {
246 return ptr_ < rhs.get();
247 }
248
249 protected:
250 T* ptr_ = nullptr;
251
252 private:
253 template <typename U>
254 friend scoped_refptr<U> base::AdoptRef(U*);
255
scoped_refptr(T * p,base::subtle::AdoptRefTag)256 scoped_refptr(T* p, base::subtle::AdoptRefTag) : ptr_(p) {}
257
258 // Friend required for move constructors that set r.ptr_ to null.
259 template <typename U>
260 friend class scoped_refptr;
261
262 // Non-inline helpers to allow:
263 // class Opaque;
264 // extern template class scoped_refptr<Opaque>;
265 // Otherwise the compiler will complain that Opaque is an incomplete type.
266 static void AddRef(T* ptr);
267 static void Release(T* ptr);
268 };
269
270 // static
271 template <typename T>
AddRef(T * ptr)272 void scoped_refptr<T>::AddRef(T* ptr) {
273 ptr->AddRef();
274 }
275
276 // static
277 template <typename T>
Release(T * ptr)278 void scoped_refptr<T>::Release(T* ptr) {
279 ptr->Release();
280 }
281
282 template <typename T, typename U>
283 bool operator==(const scoped_refptr<T>& lhs, const U* rhs) {
284 return lhs.get() == rhs;
285 }
286
287 template <typename T, typename U>
288 bool operator==(const T* lhs, const scoped_refptr<U>& rhs) {
289 return lhs == rhs.get();
290 }
291
292 template <typename T>
293 bool operator==(const scoped_refptr<T>& lhs, std::nullptr_t null) {
294 return !static_cast<bool>(lhs);
295 }
296
297 template <typename T>
298 bool operator==(std::nullptr_t null, const scoped_refptr<T>& rhs) {
299 return !static_cast<bool>(rhs);
300 }
301
302 template <typename T, typename U>
303 bool operator!=(const scoped_refptr<T>& lhs, const U* rhs) {
304 return !operator==(lhs, rhs);
305 }
306
307 template <typename T, typename U>
308 bool operator!=(const T* lhs, const scoped_refptr<U>& rhs) {
309 return !operator==(lhs, rhs);
310 }
311
312 template <typename T>
313 bool operator!=(const scoped_refptr<T>& lhs, std::nullptr_t null) {
314 return !operator==(lhs, null);
315 }
316
317 template <typename T>
318 bool operator!=(std::nullptr_t null, const scoped_refptr<T>& rhs) {
319 return !operator==(null, rhs);
320 }
321
322 template <typename T>
323 std::ostream& operator<<(std::ostream& out, const scoped_refptr<T>& p) {
324 return out << p.get();
325 }
326
327 template <typename T>
swap(scoped_refptr<T> & lhs,scoped_refptr<T> & rhs)328 void swap(scoped_refptr<T>& lhs, scoped_refptr<T>& rhs) noexcept {
329 lhs.swap(rhs);
330 }
331
332 #endif // BASE_MEMORY_SCOPED_REFPTR_H_
333