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