Bug 1832850 - Part 3: Remove an unnecessary include and some unnecessary forward...
[gecko.git] / mfbt / UniquePtr.h
blobdadb079eb9213c29c98f32acf759e7b1b8e40cd7
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* Smart pointer managing sole ownership of a resource. */
9 #ifndef mozilla_UniquePtr_h
10 #define mozilla_UniquePtr_h
12 #include <type_traits>
13 #include <utility>
15 #include "mozilla/Assertions.h"
16 #include "mozilla/Attributes.h"
17 #include "mozilla/CompactPair.h"
18 #include "mozilla/Compiler.h"
20 namespace mozilla {
22 template <typename T>
23 class DefaultDelete;
24 template <typename T, class D = DefaultDelete<T>>
25 class UniquePtr;
27 } // namespace mozilla
29 namespace mozilla {
31 namespace detail {
33 struct HasPointerTypeHelper {
34 template <class U>
35 static double Test(...);
36 template <class U>
37 static char Test(typename U::pointer* = 0);
40 template <class T>
41 class HasPointerType
42 : public std::integral_constant<bool, sizeof(HasPointerTypeHelper::Test<T>(
43 0)) == 1> {};
45 template <class T, class D, bool = HasPointerType<D>::value>
46 struct PointerTypeImpl {
47 typedef typename D::pointer Type;
50 template <class T, class D>
51 struct PointerTypeImpl<T, D, false> {
52 typedef T* Type;
55 template <class T, class D>
56 struct PointerType {
57 typedef typename PointerTypeImpl<T, std::remove_reference_t<D>>::Type Type;
60 } // namespace detail
62 /**
63 * UniquePtr is a smart pointer that wholly owns a resource. Ownership may be
64 * transferred out of a UniquePtr through explicit action, but otherwise the
65 * resource is destroyed when the UniquePtr is destroyed.
67 * UniquePtr is similar to C++98's std::auto_ptr, but it improves upon auto_ptr
68 * in one crucial way: it's impossible to copy a UniquePtr. Copying an auto_ptr
69 * obviously *can't* copy ownership of its singly-owned resource. So what
70 * happens if you try to copy one? Bizarrely, ownership is implicitly
71 * *transferred*, preserving single ownership but breaking code that assumes a
72 * copy of an object is identical to the original. (This is why auto_ptr is
73 * prohibited in STL containers.)
75 * UniquePtr solves this problem by being *movable* rather than copyable.
76 * Instead of passing a |UniquePtr u| directly to the constructor or assignment
77 * operator, you pass |Move(u)|. In doing so you indicate that you're *moving*
78 * ownership out of |u|, into the target of the construction/assignment. After
79 * the transfer completes, |u| contains |nullptr| and may be safely destroyed.
80 * This preserves single ownership but also allows UniquePtr to be moved by
81 * algorithms that have been made move-safe. (Note: if |u| is instead a
82 * temporary expression, don't use |Move()|: just pass the expression, because
83 * it's already move-ready. For more information see Move.h.)
85 * UniquePtr is also better than std::auto_ptr in that the deletion operation is
86 * customizable. An optional second template parameter specifies a class that
87 * (through its operator()(T*)) implements the desired deletion policy. If no
88 * policy is specified, mozilla::DefaultDelete<T> is used -- which will either
89 * |delete| or |delete[]| the resource, depending whether the resource is an
90 * array. Custom deletion policies ideally should be empty classes (no member
91 * fields, no member fields in base classes, no virtual methods/inheritance),
92 * because then UniquePtr can be just as efficient as a raw pointer.
94 * Use of UniquePtr proceeds like so:
96 * UniquePtr<int> g1; // initializes to nullptr
97 * g1.reset(new int); // switch resources using reset()
98 * g1 = nullptr; // clears g1, deletes the int
100 * UniquePtr<int> g2(new int); // owns that int
101 * int* p = g2.release(); // g2 leaks its int -- still requires deletion
102 * delete p; // now freed
104 * struct S { int x; S(int x) : x(x) {} };
105 * UniquePtr<S> g3, g4(new S(5));
106 * g3 = std::move(g4); // g3 owns the S, g4 cleared
107 * S* p = g3.get(); // g3 still owns |p|
108 * assert(g3->x == 5); // operator-> works (if .get() != nullptr)
109 * assert((*g3).x == 5); // also operator* (again, if not cleared)
110 * std::swap(g3, g4); // g4 now owns the S, g3 cleared
111 * g3.swap(g4); // g3 now owns the S, g4 cleared
112 * UniquePtr<S> g5(std::move(g3)); // g5 owns the S, g3 cleared
113 * g5.reset(); // deletes the S, g5 cleared
115 * struct FreePolicy { void operator()(void* p) { free(p); } };
116 * UniquePtr<int, FreePolicy> g6(static_cast<int*>(malloc(sizeof(int))));
117 * int* ptr = g6.get();
118 * g6 = nullptr; // calls free(ptr)
120 * Now, carefully note a few things you *can't* do:
122 * UniquePtr<int> b1;
123 * b1 = new int; // BAD: can only assign another UniquePtr
124 * int* ptr = b1; // BAD: no auto-conversion to pointer, use get()
126 * UniquePtr<int> b2(b1); // BAD: can't copy a UniquePtr
127 * UniquePtr<int> b3 = b1; // BAD: can't copy-assign a UniquePtr
129 * (Note that changing a UniquePtr to store a direct |new| expression is
130 * permitted, but usually you should use MakeUnique, defined at the end of this
131 * header.)
133 * A few miscellaneous notes:
135 * UniquePtr, when not instantiated for an array type, can be move-constructed
136 * and move-assigned, not only from itself but from "derived" UniquePtr<U, E>
137 * instantiations where U converts to T and E converts to D. If you want to use
138 * this, you're going to have to specify a deletion policy for both UniquePtr
139 * instantations, and T pretty much has to have a virtual destructor. In other
140 * words, this doesn't work:
142 * struct Base { virtual ~Base() {} };
143 * struct Derived : Base {};
145 * UniquePtr<Base> b1;
146 * // BAD: DefaultDelete<Base> and DefaultDelete<Derived> don't interconvert
147 * UniquePtr<Derived> d1(std::move(b));
149 * UniquePtr<Base> b2;
150 * UniquePtr<Derived, DefaultDelete<Base>> d2(std::move(b2)); // okay
152 * UniquePtr is specialized for array types. Specializing with an array type
153 * creates a smart-pointer version of that array -- not a pointer to such an
154 * array.
156 * UniquePtr<int[]> arr(new int[5]);
157 * arr[0] = 4;
159 * What else is different? Deletion of course uses |delete[]|. An operator[]
160 * is provided. Functionality that doesn't make sense for arrays is removed.
161 * The constructors and mutating methods only accept array pointers (not T*, U*
162 * that converts to T*, or UniquePtr<U[]> or UniquePtr<U>) or |nullptr|.
164 * It's perfectly okay for a function to return a UniquePtr. This transfers
165 * the UniquePtr's sole ownership of the data, to the fresh UniquePtr created
166 * in the calling function, that will then solely own that data. Such functions
167 * can return a local variable UniquePtr, |nullptr|, |UniquePtr(ptr)| where
168 * |ptr| is a |T*|, or a UniquePtr |Move()|'d from elsewhere.
170 * UniquePtr will commonly be a member of a class, with lifetime equivalent to
171 * that of that class. If you want to expose the related resource, you could
172 * expose a raw pointer via |get()|, but ownership of a raw pointer is
173 * inherently unclear. So it's better to expose a |const UniquePtr&| instead.
174 * This prohibits mutation but still allows use of |get()| when needed (but
175 * operator-> is preferred). Of course, you can only use this smart pointer as
176 * long as the enclosing class instance remains live -- no different than if you
177 * exposed the |get()| raw pointer.
179 * To pass a UniquePtr-managed resource as a pointer, use a |const UniquePtr&|
180 * argument. To specify an inout parameter (where the method may or may not
181 * take ownership of the resource, or reset it), or to specify an out parameter
182 * (where simply returning a |UniquePtr| isn't possible), use a |UniquePtr&|
183 * argument. To unconditionally transfer ownership of a UniquePtr
184 * into a method, use a |UniquePtr| argument. To conditionally transfer
185 * ownership of a resource into a method, should the method want it, use a
186 * |UniquePtr&&| argument.
188 template <typename T, class D>
189 class UniquePtr {
190 public:
191 typedef T ElementType;
192 typedef D DeleterType;
193 typedef typename detail::PointerType<T, DeleterType>::Type Pointer;
195 private:
196 mozilla::CompactPair<Pointer, DeleterType> mTuple;
198 Pointer& ptr() { return mTuple.first(); }
199 const Pointer& ptr() const { return mTuple.first(); }
201 DeleterType& del() { return mTuple.second(); }
202 const DeleterType& del() const { return mTuple.second(); }
204 public:
206 * Construct a UniquePtr containing |nullptr|.
208 constexpr UniquePtr() : mTuple(static_cast<Pointer>(nullptr), DeleterType()) {
209 static_assert(!std::is_pointer_v<D>, "must provide a deleter instance");
210 static_assert(!std::is_reference_v<D>, "must provide a deleter instance");
214 * Construct a UniquePtr containing |aPtr|.
216 explicit UniquePtr(Pointer aPtr) : mTuple(aPtr, DeleterType()) {
217 static_assert(!std::is_pointer_v<D>, "must provide a deleter instance");
218 static_assert(!std::is_reference_v<D>, "must provide a deleter instance");
221 UniquePtr(Pointer aPtr,
222 std::conditional_t<std::is_reference_v<D>, D, const D&> aD1)
223 : mTuple(aPtr, aD1) {}
225 UniquePtr(Pointer aPtr, std::remove_reference_t<D>&& aD2)
226 : mTuple(aPtr, std::move(aD2)) {
227 static_assert(!std::is_reference_v<D>,
228 "rvalue deleter can't be stored by reference");
231 UniquePtr(UniquePtr&& aOther)
232 : mTuple(aOther.release(),
233 std::forward<DeleterType>(aOther.get_deleter())) {}
235 MOZ_IMPLICIT constexpr UniquePtr(decltype(nullptr)) : UniquePtr() {}
237 template <typename U, class E>
238 MOZ_IMPLICIT UniquePtr(
239 UniquePtr<U, E>&& aOther,
240 std::enable_if_t<
241 std::is_convertible_v<typename UniquePtr<U, E>::Pointer, Pointer> &&
242 !std::is_array_v<U> &&
243 (std::is_reference_v<D> ? std::is_same_v<D, E>
244 : std::is_convertible_v<E, D>),
245 int>
246 aDummy = 0)
247 : mTuple(aOther.release(), std::forward<E>(aOther.get_deleter())) {}
249 ~UniquePtr() { reset(nullptr); }
251 UniquePtr& operator=(UniquePtr&& aOther) {
252 reset(aOther.release());
253 get_deleter() = std::forward<DeleterType>(aOther.get_deleter());
254 return *this;
257 template <typename U, typename E>
258 UniquePtr& operator=(UniquePtr<U, E>&& aOther) {
259 static_assert(
260 std::is_convertible_v<typename UniquePtr<U, E>::Pointer, Pointer>,
261 "incompatible UniquePtr pointees");
262 static_assert(!std::is_array_v<U>,
263 "can't assign from UniquePtr holding an array");
265 reset(aOther.release());
266 get_deleter() = std::forward<E>(aOther.get_deleter());
267 return *this;
270 UniquePtr& operator=(decltype(nullptr)) {
271 reset(nullptr);
272 return *this;
275 std::add_lvalue_reference_t<T> operator*() const {
276 MOZ_ASSERT(get(), "dereferencing a UniquePtr containing nullptr with *");
277 return *get();
279 Pointer operator->() const {
280 MOZ_ASSERT(get(), "dereferencing a UniquePtr containing nullptr with ->");
281 return get();
284 explicit operator bool() const { return get() != nullptr; }
286 Pointer get() const { return ptr(); }
288 DeleterType& get_deleter() { return del(); }
289 const DeleterType& get_deleter() const { return del(); }
291 [[nodiscard]] Pointer release() {
292 Pointer p = ptr();
293 ptr() = nullptr;
294 return p;
297 void reset(Pointer aPtr = Pointer()) {
298 Pointer old = ptr();
299 ptr() = aPtr;
300 if (old != nullptr) {
301 get_deleter()(old);
305 void swap(UniquePtr& aOther) { mTuple.swap(aOther.mTuple); }
307 UniquePtr(const UniquePtr& aOther) = delete; // construct using std::move()!
308 void operator=(const UniquePtr& aOther) =
309 delete; // assign using std::move()!
312 // In case you didn't read the comment by the main definition (you should!): the
313 // UniquePtr<T[]> specialization exists to manage array pointers. It deletes
314 // such pointers using delete[], it will reject construction and modification
315 // attempts using U* or U[]. Otherwise it works like the normal UniquePtr.
316 template <typename T, class D>
317 class UniquePtr<T[], D> {
318 public:
319 typedef T* Pointer;
320 typedef T ElementType;
321 typedef D DeleterType;
323 private:
324 mozilla::CompactPair<Pointer, DeleterType> mTuple;
326 public:
328 * Construct a UniquePtr containing nullptr.
330 constexpr UniquePtr() : mTuple(static_cast<Pointer>(nullptr), DeleterType()) {
331 static_assert(!std::is_pointer_v<D>, "must provide a deleter instance");
332 static_assert(!std::is_reference_v<D>, "must provide a deleter instance");
336 * Construct a UniquePtr containing |aPtr|.
338 explicit UniquePtr(Pointer aPtr) : mTuple(aPtr, DeleterType()) {
339 static_assert(!std::is_pointer_v<D>, "must provide a deleter instance");
340 static_assert(!std::is_reference_v<D>, "must provide a deleter instance");
343 // delete[] knows how to handle *only* an array of a single class type. For
344 // delete[] to work correctly, it must know the size of each element, the
345 // fields and base classes of each element requiring destruction, and so on.
346 // So forbid all overloads which would end up invoking delete[] on a pointer
347 // of the wrong type.
348 template <typename U>
349 UniquePtr(U&& aU,
350 std::enable_if_t<
351 std::is_pointer_v<U> && std::is_convertible_v<U, Pointer>, int>
352 aDummy = 0) = delete;
354 UniquePtr(Pointer aPtr,
355 std::conditional_t<std::is_reference_v<D>, D, const D&> aD1)
356 : mTuple(aPtr, aD1) {}
358 UniquePtr(Pointer aPtr, std::remove_reference_t<D>&& aD2)
359 : mTuple(aPtr, std::move(aD2)) {
360 static_assert(!std::is_reference_v<D>,
361 "rvalue deleter can't be stored by reference");
364 // Forbidden for the same reasons as stated above.
365 template <typename U, typename V>
366 UniquePtr(U&& aU, V&& aV,
367 std::enable_if_t<
368 std::is_pointer_v<U> && std::is_convertible_v<U, Pointer>, int>
369 aDummy = 0) = delete;
371 UniquePtr(UniquePtr&& aOther)
372 : mTuple(aOther.release(),
373 std::forward<DeleterType>(aOther.get_deleter())) {}
375 MOZ_IMPLICIT
376 UniquePtr(decltype(nullptr)) : mTuple(nullptr, DeleterType()) {
377 static_assert(!std::is_pointer_v<D>, "must provide a deleter instance");
378 static_assert(!std::is_reference_v<D>, "must provide a deleter instance");
381 ~UniquePtr() { reset(nullptr); }
383 UniquePtr& operator=(UniquePtr&& aOther) {
384 reset(aOther.release());
385 get_deleter() = std::forward<DeleterType>(aOther.get_deleter());
386 return *this;
389 UniquePtr& operator=(decltype(nullptr)) {
390 reset();
391 return *this;
394 explicit operator bool() const { return get() != nullptr; }
396 T& operator[](decltype(sizeof(int)) aIndex) const { return get()[aIndex]; }
397 Pointer get() const { return mTuple.first(); }
399 DeleterType& get_deleter() { return mTuple.second(); }
400 const DeleterType& get_deleter() const { return mTuple.second(); }
402 [[nodiscard]] Pointer release() {
403 Pointer p = mTuple.first();
404 mTuple.first() = nullptr;
405 return p;
408 void reset(Pointer aPtr = Pointer()) {
409 Pointer old = mTuple.first();
410 mTuple.first() = aPtr;
411 if (old != nullptr) {
412 mTuple.second()(old);
416 void reset(decltype(nullptr)) {
417 Pointer old = mTuple.first();
418 mTuple.first() = nullptr;
419 if (old != nullptr) {
420 mTuple.second()(old);
424 template <typename U>
425 void reset(U) = delete;
427 void swap(UniquePtr& aOther) { mTuple.swap(aOther.mTuple); }
429 UniquePtr(const UniquePtr& aOther) = delete; // construct using std::move()!
430 void operator=(const UniquePtr& aOther) =
431 delete; // assign using std::move()!
435 * A default deletion policy using plain old operator delete.
437 * Note that this type can be specialized, but authors should beware of the risk
438 * that the specialization may at some point cease to match (either because it
439 * gets moved to a different compilation unit or the signature changes). If the
440 * non-specialized (|delete|-based) version compiles for that type but does the
441 * wrong thing, bad things could happen.
443 * This is a non-issue for types which are always incomplete (i.e. opaque handle
444 * types), since |delete|-ing such a type will always trigger a compilation
445 * error.
447 template <typename T>
448 class DefaultDelete {
449 public:
450 constexpr DefaultDelete() = default;
452 template <typename U>
453 MOZ_IMPLICIT DefaultDelete(
454 const DefaultDelete<U>& aOther,
455 std::enable_if_t<std::is_convertible_v<U*, T*>, int> aDummy = 0) {}
457 void operator()(T* aPtr) const {
458 static_assert(sizeof(T) > 0, "T must be complete");
459 delete aPtr;
463 /** A default deletion policy using operator delete[]. */
464 template <typename T>
465 class DefaultDelete<T[]> {
466 public:
467 constexpr DefaultDelete() = default;
469 void operator()(T* aPtr) const {
470 static_assert(sizeof(T) > 0, "T must be complete");
471 delete[] aPtr;
474 template <typename U>
475 void operator()(U* aPtr) const = delete;
478 template <typename T, class D, typename U, class E>
479 bool operator==(const UniquePtr<T, D>& aX, const UniquePtr<U, E>& aY) {
480 return aX.get() == aY.get();
483 template <typename T, class D, typename U, class E>
484 bool operator!=(const UniquePtr<T, D>& aX, const UniquePtr<U, E>& aY) {
485 return aX.get() != aY.get();
488 template <typename T, class D>
489 bool operator==(const UniquePtr<T, D>& aX, const T* aY) {
490 return aX.get() == aY;
493 template <typename T, class D>
494 bool operator==(const T* aY, const UniquePtr<T, D>& aX) {
495 return aY == aX.get();
498 template <typename T, class D>
499 bool operator!=(const UniquePtr<T, D>& aX, const T* aY) {
500 return aX.get() != aY;
503 template <typename T, class D>
504 bool operator!=(const T* aY, const UniquePtr<T, D>& aX) {
505 return aY != aX.get();
508 template <typename T, class D>
509 bool operator==(const UniquePtr<T, D>& aX, decltype(nullptr)) {
510 return !aX;
513 template <typename T, class D>
514 bool operator==(decltype(nullptr), const UniquePtr<T, D>& aX) {
515 return !aX;
518 template <typename T, class D>
519 bool operator!=(const UniquePtr<T, D>& aX, decltype(nullptr)) {
520 return bool(aX);
523 template <typename T, class D>
524 bool operator!=(decltype(nullptr), const UniquePtr<T, D>& aX) {
525 return bool(aX);
528 // No operator<, operator>, operator<=, operator>= for now because simplicity.
530 namespace detail {
532 template <typename T>
533 struct UniqueSelector {
534 typedef UniquePtr<T> SingleObject;
537 template <typename T>
538 struct UniqueSelector<T[]> {
539 typedef UniquePtr<T[]> UnknownBound;
542 template <typename T, decltype(sizeof(int)) N>
543 struct UniqueSelector<T[N]> {
544 typedef UniquePtr<T[N]> KnownBound;
547 } // namespace detail
550 * MakeUnique is a helper function for allocating new'd objects and arrays,
551 * returning a UniquePtr containing the resulting pointer. The semantics of
552 * MakeUnique<Type>(...) are as follows.
554 * If Type is an array T[n]:
555 * Disallowed, deleted, no overload for you!
556 * If Type is an array T[]:
557 * MakeUnique<T[]>(size_t) is the only valid overload. The pointer returned
558 * is as if by |new T[n]()|, which value-initializes each element. (If T
559 * isn't a class type, this will zero each element. If T is a class type,
560 * then roughly speaking, each element will be constructed using its default
561 * constructor. See C++11 [dcl.init]p7 for the full gory details.)
562 * If Type is non-array T:
563 * The arguments passed to MakeUnique<T>(...) are forwarded into a
564 * |new T(...)| call, initializing the T as would happen if executing
565 * |T(...)|.
567 * There are various benefits to using MakeUnique instead of |new| expressions.
569 * First, MakeUnique eliminates use of |new| from code entirely. If objects are
570 * only created through UniquePtr, then (assuming all explicit release() calls
571 * are safe, including transitively, and no type-safety casting funniness)
572 * correctly maintained ownership of the UniquePtr guarantees no leaks are
573 * possible. (This pays off best if a class is only ever created through a
574 * factory method on the class, using a private constructor.)
576 * Second, initializing a UniquePtr using a |new| expression requires repeating
577 * the name of the new'd type, whereas MakeUnique in concert with the |auto|
578 * keyword names it only once:
580 * UniquePtr<char> ptr1(new char()); // repetitive
581 * auto ptr2 = MakeUnique<char>(); // shorter
583 * Of course this assumes the reader understands the operation MakeUnique
584 * performs. In the long run this is probably a reasonable assumption. In the
585 * short run you'll have to use your judgment about what readers can be expected
586 * to know, or to quickly look up.
588 * Third, a call to MakeUnique can be assigned directly to a UniquePtr. In
589 * contrast you can't assign a pointer into a UniquePtr without using the
590 * cumbersome reset().
592 * UniquePtr<char> p;
593 * p = new char; // ERROR
594 * p.reset(new char); // works, but fugly
595 * p = MakeUnique<char>(); // preferred
597 * (And third, although not relevant to Mozilla: MakeUnique is exception-safe.
598 * An exception thrown after |new T| succeeds will leak that memory, unless the
599 * pointer is assigned to an object that will manage its ownership. UniquePtr
600 * ably serves this function.)
603 template <typename T, typename... Args>
604 typename detail::UniqueSelector<T>::SingleObject MakeUnique(Args&&... aArgs) {
605 return UniquePtr<T>(new T(std::forward<Args>(aArgs)...));
608 template <typename T>
609 typename detail::UniqueSelector<T>::UnknownBound MakeUnique(
610 decltype(sizeof(int)) aN) {
611 using ArrayType = std::remove_extent_t<T>;
612 return UniquePtr<T>(new ArrayType[aN]());
615 template <typename T, typename... Args>
616 typename detail::UniqueSelector<T>::KnownBound MakeUnique(Args&&... aArgs) =
617 delete;
620 * WrapUnique is a helper function to transfer ownership from a raw pointer
621 * into a UniquePtr<T>. It can only be used with a single non-array type.
623 * It is generally used this way:
625 * auto p = WrapUnique(new char);
627 * It can be used when MakeUnique is not usable, for example, when the
628 * constructor you are using is private, or you want to use aggregate
629 * initialization.
632 template <typename T>
633 typename detail::UniqueSelector<T>::SingleObject WrapUnique(T* aPtr) {
634 return UniquePtr<T>(aPtr);
637 } // namespace mozilla
639 namespace std {
641 template <typename T, class D>
642 void swap(mozilla::UniquePtr<T, D>& aX, mozilla::UniquePtr<T, D>& aY) {
643 aX.swap(aY);
646 } // namespace std
648 #endif /* mozilla_UniquePtr_h */