| 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/. */ |
| 6 |
|
| 7 |
/* Smart pointer managing sole ownership of a resource. */ |
| 8 |
|
| 9 |
#ifndef mozilla_UniquePtr_h |
| 10 |
#define mozilla_UniquePtr_h |
| 11 |
|
| 12 |
#include <memory> |
| 13 |
#include <type_traits> |
| 14 |
#include <utility> |
| 15 |
|
| 16 |
#include "mozilla/Assertions.h" |
| 17 |
#include "mozilla/Attributes.h" |
| 18 |
#include "mozilla/CompactPair.h" |
| 19 |
#include "mozilla/Compiler.h" |
| 20 |
|
| 21 |
namespace mozilla { |
| 22 |
|
| 23 |
template <typename T> |
| 24 |
class DefaultDelete; |
| 25 |
template <typename T, class D = DefaultDelete<T>> |
| 26 |
class UniquePtr; |
| 27 |
|
| 28 |
} // namespace mozilla |
| 29 |
|
| 30 |
namespace mozilla { |
| 31 |
|
| 32 |
namespace detail { |
| 33 |
|
| 34 |
struct HasPointerTypeHelper { |
| 35 |
template <class U> |
| 36 |
static double Test(...); |
| 37 |
template <class U> |
| 38 |
static char Test(typename U::pointer* = 0); |
| 39 |
}; |
| 40 |
|
| 41 |
template <class T> |
| 42 |
class HasPointerType |
| 43 |
: public std::integral_constant<bool, sizeof(HasPointerTypeHelper::Test<T>( |
| 44 |
0)) == 1> {}; |
| 45 |
|
| 46 |
template <class T, class D, bool = HasPointerType<D>::value> |
| 47 |
struct PointerTypeImpl { |
| 48 |
typedef typename D::pointer Type; |
| 49 |
}; |
| 50 |
|
| 51 |
template <class T, class D> |
| 52 |
struct PointerTypeImpl<T, D, false> { |
| 53 |
typedef T* Type; |
| 54 |
}; |
| 55 |
|
| 56 |
template <class T, class D> |
| 57 |
struct PointerType { |
| 58 |
typedef typename PointerTypeImpl<T, std::remove_reference_t<D>>::Type Type; |
| 59 |
}; |
| 60 |
|
| 61 |
} // namespace detail |
| 62 |
|
| 63 |
/** |
| 64 |
* UniquePtr is a smart pointer that wholly owns a resource. Ownership may be |
| 65 |
* transferred out of a UniquePtr through explicit action, but otherwise the |
| 66 |
* resource is destroyed when the UniquePtr is destroyed. |
| 67 |
* |
| 68 |
* UniquePtr is similar to C++98's std::auto_ptr, but it improves upon auto_ptr |
| 69 |
* in one crucial way: it's impossible to copy a UniquePtr. Copying an auto_ptr |
| 70 |
* obviously *can't* copy ownership of its singly-owned resource. So what |
| 71 |
* happens if you try to copy one? Bizarrely, ownership is implicitly |
| 72 |
* *transferred*, preserving single ownership but breaking code that assumes a |
| 73 |
* copy of an object is identical to the original. (This is why auto_ptr is |
| 74 |
* prohibited in STL containers.) |
| 75 |
* |
| 76 |
* UniquePtr solves this problem by being *movable* rather than copyable. |
| 77 |
* Instead of passing a |UniquePtr u| directly to the constructor or assignment |
| 78 |
* operator, you pass |Move(u)|. In doing so you indicate that you're *moving* |
| 79 |
* ownership out of |u|, into the target of the construction/assignment. After |
| 80 |
* the transfer completes, |u| contains |nullptr| and may be safely destroyed. |
| 81 |
* This preserves single ownership but also allows UniquePtr to be moved by |
| 82 |
* algorithms that have been made move-safe. (Note: if |u| is instead a |
| 83 |
* temporary expression, don't use |Move()|: just pass the expression, because |
| 84 |
* it's already move-ready. For more information see Move.h.) |
| 85 |
* |
| 86 |
* UniquePtr is also better than std::auto_ptr in that the deletion operation is |
| 87 |
* customizable. An optional second template parameter specifies a class that |
| 88 |
* (through its operator()(T*)) implements the desired deletion policy. If no |
| 89 |
* policy is specified, mozilla::DefaultDelete<T> is used -- which will either |
| 90 |
* |delete| or |delete[]| the resource, depending whether the resource is an |
| 91 |
* array. Custom deletion policies ideally should be empty classes (no member |
| 92 |
* fields, no member fields in base classes, no virtual methods/inheritance), |
| 93 |
* because then UniquePtr can be just as efficient as a raw pointer. |
| 94 |
* |
| 95 |
* Use of UniquePtr proceeds like so: |
| 96 |
* |
| 97 |
* UniquePtr<int> g1; // initializes to nullptr |
| 98 |
* g1.reset(new int); // switch resources using reset() |
| 99 |
* g1 = nullptr; // clears g1, deletes the int |
| 100 |
* |
| 101 |
* UniquePtr<int> g2(new int); // owns that int |
| 102 |
* int* p = g2.release(); // g2 leaks its int -- still requires deletion |
| 103 |
* delete p; // now freed |
| 104 |
* |
| 105 |
* struct S { int x; S(int x) : x(x) {} }; |
| 106 |
* UniquePtr<S> g3, g4(new S(5)); |
| 107 |
* g3 = std::move(g4); // g3 owns the S, g4 cleared |
| 108 |
* S* p = g3.get(); // g3 still owns |p| |
| 109 |
* assert(g3->x == 5); // operator-> works (if .get() != nullptr) |
| 110 |
* assert((*g3).x == 5); // also operator* (again, if not cleared) |
| 111 |
* std::swap(g3, g4); // g4 now owns the S, g3 cleared |
| 112 |
* g3.swap(g4); // g3 now owns the S, g4 cleared |
| 113 |
* UniquePtr<S> g5(std::move(g3)); // g5 owns the S, g3 cleared |
| 114 |
* g5.reset(); // deletes the S, g5 cleared |
| 115 |
* |
| 116 |
* struct FreePolicy { void operator()(void* p) { free(p); } }; |
| 117 |
* UniquePtr<int, FreePolicy> g6(static_cast<int*>(malloc(sizeof(int)))); |
| 118 |
* int* ptr = g6.get(); |
| 119 |
* g6 = nullptr; // calls free(ptr) |
| 120 |
* |
| 121 |
* Now, carefully note a few things you *can't* do: |
| 122 |
* |
| 123 |
* UniquePtr<int> b1; |
| 124 |
* b1 = new int; // BAD: can only assign another UniquePtr |
| 125 |
* int* ptr = b1; // BAD: no auto-conversion to pointer, use get() |
| 126 |
* |
| 127 |
* UniquePtr<int> b2(b1); // BAD: can't copy a UniquePtr |
| 128 |
* UniquePtr<int> b3 = b1; // BAD: can't copy-assign a UniquePtr |
| 129 |
* |
| 130 |
* (Note that changing a UniquePtr to store a direct |new| expression is |
| 131 |
* permitted, but usually you should use MakeUnique, defined at the end of this |
| 132 |
* header.) |
| 133 |
* |
| 134 |
* A few miscellaneous notes: |
| 135 |
* |
| 136 |
* UniquePtr, when not instantiated for an array type, can be move-constructed |
| 137 |
* and move-assigned, not only from itself but from "derived" UniquePtr<U, E> |
| 138 |
* instantiations where U converts to T and E converts to D. If you want to use |
| 139 |
* this, you're going to have to specify a deletion policy for both UniquePtr |
| 140 |
* instantations, and T pretty much has to have a virtual destructor. In other |
| 141 |
* words, this doesn't work: |
| 142 |
* |
| 143 |
* struct Base { virtual ~Base() {} }; |
| 144 |
* struct Derived : Base {}; |
| 145 |
* |
| 146 |
* UniquePtr<Base> b1; |
| 147 |
* // BAD: DefaultDelete<Base> and DefaultDelete<Derived> don't interconvert |
| 148 |
* UniquePtr<Derived> d1(std::move(b)); |
| 149 |
* |
| 150 |
* UniquePtr<Base> b2; |
| 151 |
* UniquePtr<Derived, DefaultDelete<Base>> d2(std::move(b2)); // okay |
| 152 |
* |
| 153 |
* UniquePtr is specialized for array types. Specializing with an array type |
| 154 |
* creates a smart-pointer version of that array -- not a pointer to such an |
| 155 |
* array. |
| 156 |
* |
| 157 |
* UniquePtr<int[]> arr(new int[5]); |
| 158 |
* arr[0] = 4; |
| 159 |
* |
| 160 |
* What else is different? Deletion of course uses |delete[]|. An operator[] |
| 161 |
* is provided. Functionality that doesn't make sense for arrays is removed. |
| 162 |
* The constructors and mutating methods only accept array pointers (not T*, U* |
| 163 |
* that converts to T*, or UniquePtr<U[]> or UniquePtr<U>) or |nullptr|. |
| 164 |
* |
| 165 |
* It's perfectly okay for a function to return a UniquePtr. This transfers |
| 166 |
* the UniquePtr's sole ownership of the data, to the fresh UniquePtr created |
| 167 |
* in the calling function, that will then solely own that data. Such functions |
| 168 |
* can return a local variable UniquePtr, |nullptr|, |UniquePtr(ptr)| where |
| 169 |
* |ptr| is a |T*|, or a UniquePtr |Move()|'d from elsewhere. |
| 170 |
* |
| 171 |
* UniquePtr will commonly be a member of a class, with lifetime equivalent to |
| 172 |
* that of that class. If you want to expose the related resource, you could |
| 173 |
* expose a raw pointer via |get()|, but ownership of a raw pointer is |
| 174 |
* inherently unclear. So it's better to expose a |const UniquePtr&| instead. |
| 175 |
* This prohibits mutation but still allows use of |get()| when needed (but |
| 176 |
* operator-> is preferred). Of course, you can only use this smart pointer as |
| 177 |
* long as the enclosing class instance remains live -- no different than if you |
| 178 |
* exposed the |get()| raw pointer. |
| 179 |
* |
| 180 |
* To pass a UniquePtr-managed resource as a pointer, use a |const UniquePtr&| |
| 181 |
* argument. To specify an inout parameter (where the method may or may not |
| 182 |
* take ownership of the resource, or reset it), or to specify an out parameter |
| 183 |
* (where simply returning a |UniquePtr| isn't possible), use a |UniquePtr&| |
| 184 |
* argument. To unconditionally transfer ownership of a UniquePtr |
| 185 |
* into a method, use a |UniquePtr| argument. To conditionally transfer |
| 186 |
* ownership of a resource into a method, should the method want it, use a |
| 187 |
* |UniquePtr&&| argument. |
| 188 |
*/ |
| 189 |
template <typename T, class D> |
| 190 |
class MOZ_GSL_OWNER UniquePtr { |
| 191 |
public: |
| 192 |
typedef T ElementType; |
| 193 |
typedef D DeleterType; |
| 194 |
typedef typename detail::PointerType<T, DeleterType>::Type Pointer; |
| 195 |
|
| 196 |
private: |
| 197 |
mozilla::CompactPair<Pointer, DeleterType> mTuple; |
| 198 |
|
| 199 |
Pointer& ptr() { return mTuple.first(); } |
| 200 |
const Pointer& ptr() const { return mTuple.first(); } |
| 201 |
|
| 202 |
DeleterType& del() { return mTuple.second(); } |
| 203 |
const DeleterType& del() const { return mTuple.second(); } |
| 204 |
|
| 205 |
public: |
| 206 |
/** |
| 207 |
* Construct a UniquePtr containing |nullptr|. |
| 208 |
*/ |
| 209 |
constexpr UniquePtr() : mTuple(static_cast<Pointer>(nullptr), DeleterType()) { |
| 210 |
static_assert(!std::is_pointer_v<D>, "must provide a deleter instance"); |
| 211 |
static_assert(!std::is_reference_v<D>, "must provide a deleter instance"); |
| 212 |
} |
| 213 |
|
| 214 |
/** |
| 215 |
* Construct a UniquePtr containing |aPtr|. |
| 216 |
*/ |
| 217 |
explicit UniquePtr(Pointer aPtr MOZ_LIFETIME_BOUND) |
| 218 |
: mTuple(aPtr, DeleterType()) { |
| 219 |
static_assert(!std::is_pointer_v<D>, "must provide a deleter instance"); |
| 220 |
static_assert(!std::is_reference_v<D>, "must provide a deleter instance"); |
| 221 |
} |
| 222 |
|
| 223 |
UniquePtr(Pointer aPtr MOZ_LIFETIME_BOUND, |
| 224 |
std::conditional_t<std::is_reference_v<D>, D, const D&> aD1) |
| 225 |
: mTuple(aPtr, aD1) {} |
| 226 |
|
| 227 |
UniquePtr(Pointer aPtr, std::remove_reference_t<D>&& aD2) |
| 228 |
: mTuple(aPtr, std::move(aD2)) { |
| 229 |
static_assert(!std::is_reference_v<D>, |
| 230 |
"rvalue deleter can't be stored by reference"); |
| 231 |
} |
| 232 |
|
| 233 |
UniquePtr(UniquePtr&& aOther) |
| 234 |
: mTuple(aOther.release(), |
| 235 |
std::forward<DeleterType>(aOther.get_deleter())) {} |
| 236 |
|
| 237 |
MOZ_IMPLICIT constexpr UniquePtr(decltype(nullptr)) : UniquePtr() {} |
| 238 |
|
| 239 |
template <typename U, class E> |
| 240 |
MOZ_IMPLICIT UniquePtr( |
| 241 |
UniquePtr<U, E>&& aOther, |
| 242 |
std::enable_if_t< |
| 243 |
std::is_convertible_v<typename UniquePtr<U, E>::Pointer, Pointer> && |
| 244 |
!std::is_array_v<U> && |
| 245 |
(std::is_reference_v<D> ? std::is_same_v<D, E> |
| 246 |
: std::is_convertible_v<E, D>), |
| 247 |
int> |
| 248 |
aDummy = 0) |
| 249 |
: mTuple(aOther.release(), std::forward<E>(aOther.get_deleter())) {} |
| 250 |
|
| 251 |
~UniquePtr() { reset(nullptr); } |
| 252 |
|
| 253 |
UniquePtr& operator=(UniquePtr&& aOther) { |
| 254 |
reset(aOther.release()); |
| 255 |
get_deleter() = std::forward<DeleterType>(aOther.get_deleter()); |
| 256 |
return *this; |
| 257 |
} |
| 258 |
|
| 259 |
template <typename U, typename E> |
| 260 |
UniquePtr& operator=(UniquePtr<U, E>&& aOther) { |
| 261 |
static_assert( |
| 262 |
std::is_convertible_v<typename UniquePtr<U, E>::Pointer, Pointer>, |
| 263 |
"incompatible UniquePtr pointees"); |
| 264 |
static_assert(!std::is_array_v<U>, |
| 265 |
"can't assign from UniquePtr holding an array"); |
| 266 |
|
| 267 |
reset(aOther.release()); |
| 268 |
get_deleter() = std::forward<E>(aOther.get_deleter()); |
| 269 |
return *this; |
| 270 |
} |
| 271 |
|
| 272 |
UniquePtr& operator=(decltype(nullptr)) { |
| 273 |
reset(nullptr); |
| 274 |
return *this; |
| 275 |
} |
| 276 |
|
| 277 |
std::add_lvalue_reference_t<T> operator*() const MOZ_LIFETIME_BOUND { |
| 278 |
MOZ_ASSERT(get(), "dereferencing a UniquePtr containing nullptr with *"); |
| 279 |
return *get(); |
| 280 |
} |
| 281 |
Pointer operator->() const MOZ_LIFETIME_BOUND { |
| 282 |
MOZ_ASSERT(get(), "dereferencing a UniquePtr containing nullptr with ->"); |
| 283 |
return get(); |
| 284 |
} |
| 285 |
|
| 286 |
explicit operator bool() const { return get() != nullptr; } |
| 287 |
|
| 288 |
Pointer get() const MOZ_LIFETIME_BOUND { return ptr(); } |
| 289 |
|
| 290 |
DeleterType& get_deleter() MOZ_LIFETIME_BOUND { return del(); } |
| 291 |
const DeleterType& get_deleter() const MOZ_LIFETIME_BOUND { return del(); } |
| 292 |
|
| 293 |
[[nodiscard]] Pointer release() { |
| 294 |
Pointer p = ptr(); |
| 295 |
ptr() = nullptr; |
| 296 |
return p; |
| 297 |
} |
| 298 |
|
| 299 |
void reset(Pointer aPtr = Pointer()) { |
| 300 |
Pointer old = ptr(); |
| 301 |
ptr() = aPtr; |
| 302 |
if (old != nullptr) { |
| 303 |
get_deleter()(old); |
| 304 |
} |
| 305 |
} |
| 306 |
|
| 307 |
void swap(UniquePtr& aOther) { mTuple.swap(aOther.mTuple); } |
| 308 |
|
| 309 |
UniquePtr(const UniquePtr& aOther) = delete; // construct using std::move()! |
| 310 |
void operator=(const UniquePtr& aOther) = |
| 311 |
delete; // assign using std::move()! |
| 312 |
}; |
| 313 |
|
| 314 |
// In case you didn't read the comment by the main definition (you should!): the |
| 315 |
// UniquePtr<T[]> specialization exists to manage array pointers. It deletes |
| 316 |
// such pointers using delete[], it will reject construction and modification |
| 317 |
// attempts using U* or U[]. Otherwise it works like the normal UniquePtr. |
| 318 |
template <typename T, class D> |
| 319 |
class UniquePtr<T[], D> { |
| 320 |
public: |
| 321 |
typedef T* Pointer; |
| 322 |
typedef T ElementType; |
| 323 |
typedef D DeleterType; |
| 324 |
|
| 325 |
private: |
| 326 |
mozilla::CompactPair<Pointer, DeleterType> mTuple; |
| 327 |
|
| 328 |
public: |
| 329 |
/** |
| 330 |
* Construct a UniquePtr containing nullptr. |
| 331 |
*/ |
| 332 |
constexpr UniquePtr() : mTuple(static_cast<Pointer>(nullptr), DeleterType()) { |
| 333 |
static_assert(!std::is_pointer_v<D>, "must provide a deleter instance"); |
| 334 |
static_assert(!std::is_reference_v<D>, "must provide a deleter instance"); |
| 335 |
} |
| 336 |
|
| 337 |
/** |
| 338 |
* Construct a UniquePtr containing |aPtr|. |
| 339 |
*/ |
| 340 |
explicit UniquePtr(Pointer aPtr) : mTuple(aPtr, DeleterType()) { |
| 341 |
static_assert(!std::is_pointer_v<D>, "must provide a deleter instance"); |
| 342 |
static_assert(!std::is_reference_v<D>, "must provide a deleter instance"); |
| 343 |
} |
| 344 |
|
| 345 |
// delete[] knows how to handle *only* an array of a single class type. For |
| 346 |
// delete[] to work correctly, it must know the size of each element, the |
| 347 |
// fields and base classes of each element requiring destruction, and so on. |
| 348 |
// So forbid all overloads which would end up invoking delete[] on a pointer |
| 349 |
// of the wrong type. |
| 350 |
template <typename U> |
| 351 |
UniquePtr(U&& aU, |
| 352 |
std::enable_if_t< |
| 353 |
std::is_pointer_v<U> && std::is_convertible_v<U, Pointer>, int> |
| 354 |
aDummy = 0) = delete; |
| 355 |
|
| 356 |
UniquePtr(Pointer aPtr, |
| 357 |
std::conditional_t<std::is_reference_v<D>, D, const D&> aD1) |
| 358 |
: mTuple(aPtr, aD1) {} |
| 359 |
|
| 360 |
UniquePtr(Pointer aPtr, std::remove_reference_t<D>&& aD2) |
| 361 |
: mTuple(aPtr, std::move(aD2)) { |
| 362 |
static_assert(!std::is_reference_v<D>, |
| 363 |
"rvalue deleter can't be stored by reference"); |
| 364 |
} |
| 365 |
|
| 366 |
// Forbidden for the same reasons as stated above. |
| 367 |
template <typename U, typename V> |
| 368 |
UniquePtr(U&& aU, V&& aV, |
| 369 |
std::enable_if_t< |
| 370 |
std::is_pointer_v<U> && std::is_convertible_v<U, Pointer>, int> |
| 371 |
aDummy = 0) = delete; |
| 372 |
|
| 373 |
UniquePtr(UniquePtr&& aOther) |
| 374 |
: mTuple(aOther.release(), |
| 375 |
std::forward<DeleterType>(aOther.get_deleter())) {} |
| 376 |
|
| 377 |
MOZ_IMPLICIT |
| 378 |
UniquePtr(decltype(nullptr)) : mTuple(nullptr, DeleterType()) { |
| 379 |
static_assert(!std::is_pointer_v<D>, "must provide a deleter instance"); |
| 380 |
static_assert(!std::is_reference_v<D>, "must provide a deleter instance"); |
| 381 |
} |
| 382 |
|
| 383 |
~UniquePtr() { reset(nullptr); } |
| 384 |
|
| 385 |
UniquePtr& operator=(UniquePtr&& aOther) { |
| 386 |
reset(aOther.release()); |
| 387 |
get_deleter() = std::forward<DeleterType>(aOther.get_deleter()); |
| 388 |
return *this; |
| 389 |
} |
| 390 |
|
| 391 |
UniquePtr& operator=(decltype(nullptr)) { |
| 392 |
reset(); |
| 393 |
return *this; |
| 394 |
} |
| 395 |
|
| 396 |
explicit operator bool() const { return get() != nullptr; } |
| 397 |
|
| 398 |
T& operator[](decltype(sizeof(int)) aIndex) const { return get()[aIndex]; } |
| 399 |
Pointer get() const { return mTuple.first(); } |
| 400 |
|
| 401 |
DeleterType& get_deleter() { return mTuple.second(); } |
| 402 |
const DeleterType& get_deleter() const { return mTuple.second(); } |
| 403 |
|
| 404 |
[[nodiscard]] Pointer release() { |
| 405 |
Pointer p = mTuple.first(); |
| 406 |
mTuple.first() = nullptr; |
| 407 |
return p; |
| 408 |
} |
| 409 |
|
| 410 |
void reset(Pointer aPtr = Pointer()) { |
| 411 |
Pointer old = mTuple.first(); |
| 412 |
mTuple.first() = aPtr; |
| 413 |
if (old != nullptr) { |
| 414 |
mTuple.second()(old); |
| 415 |
} |
| 416 |
} |
| 417 |
|
| 418 |
void reset(decltype(nullptr)) { |
| 419 |
Pointer old = mTuple.first(); |
| 420 |
mTuple.first() = nullptr; |
| 421 |
if (old != nullptr) { |
| 422 |
mTuple.second()(old); |
| 423 |
} |
| 424 |
} |
| 425 |
|
| 426 |
template <typename U> |
| 427 |
void reset(U) = delete; |
| 428 |
|
| 429 |
void swap(UniquePtr& aOther) { mTuple.swap(aOther.mTuple); } |
| 430 |
|
| 431 |
UniquePtr(const UniquePtr& aOther) = delete; // construct using std::move()! |
| 432 |
void operator=(const UniquePtr& aOther) = |
| 433 |
delete; // assign using std::move()! |
| 434 |
}; |
| 435 |
|
| 436 |
/** |
| 437 |
* A default deletion policy using plain old operator delete. |
| 438 |
* |
| 439 |
* Note that this type can be specialized, but authors should beware of the risk |
| 440 |
* that the specialization may at some point cease to match (either because it |
| 441 |
* gets moved to a different compilation unit or the signature changes). If the |
| 442 |
* non-specialized (|delete|-based) version compiles for that type but does the |
| 443 |
* wrong thing, bad things could happen. |
| 444 |
* |
| 445 |
* This is a non-issue for types which are always incomplete (i.e. opaque handle |
| 446 |
* types), since |delete|-ing such a type will always trigger a compilation |
| 447 |
* error. |
| 448 |
*/ |
| 449 |
template <typename T> |
| 450 |
class DefaultDelete { |
| 451 |
public: |
| 452 |
constexpr DefaultDelete() = default; |
| 453 |
|
| 454 |
template <typename U> |
| 455 |
MOZ_IMPLICIT DefaultDelete( |
| 456 |
const DefaultDelete<U>& aOther, |
| 457 |
std::enable_if_t<std::is_convertible_v<U*, T*>, int> aDummy = 0) {} |
| 458 |
|
| 459 |
void operator()(T* aPtr) const { |
| 460 |
static_assert(sizeof(T) > 0, "T must be complete"); |
| 461 |
delete aPtr; |
| 462 |
} |
| 463 |
}; |
| 464 |
|
| 465 |
/** A default deletion policy using operator delete[]. */ |
| 466 |
template <typename T> |
| 467 |
class DefaultDelete<T[]> { |
| 468 |
public: |
| 469 |
constexpr DefaultDelete() = default; |
| 470 |
|
| 471 |
void operator()(T* aPtr) const { |
| 472 |
static_assert(sizeof(T) > 0, "T must be complete"); |
| 473 |
delete[] aPtr; |
| 474 |
} |
| 475 |
|
| 476 |
template <typename U> |
| 477 |
void operator()(U* aPtr) const = delete; |
| 478 |
}; |
| 479 |
|
| 480 |
template <typename T, class D, typename U, class E> |
| 481 |
bool operator==(const UniquePtr<T, D>& aX, const UniquePtr<U, E>& aY) { |
| 482 |
return aX.get() == aY.get(); |
| 483 |
} |
| 484 |
|
| 485 |
template <typename T, class D, typename U, class E> |
| 486 |
bool operator!=(const UniquePtr<T, D>& aX, const UniquePtr<U, E>& aY) { |
| 487 |
return aX.get() != aY.get(); |
| 488 |
} |
| 489 |
|
| 490 |
template <typename T, class D> |
| 491 |
bool operator==(const UniquePtr<T, D>& aX, const T* aY) { |
| 492 |
return aX.get() == aY; |
| 493 |
} |
| 494 |
|
| 495 |
template <typename T, class D> |
| 496 |
bool operator==(const T* aY, const UniquePtr<T, D>& aX) { |
| 497 |
return aY == aX.get(); |
| 498 |
} |
| 499 |
|
| 500 |
template <typename T, class D> |
| 501 |
bool operator!=(const UniquePtr<T, D>& aX, const T* aY) { |
| 502 |
return aX.get() != aY; |
| 503 |
} |
| 504 |
|
| 505 |
template <typename T, class D> |
| 506 |
bool operator!=(const T* aY, const UniquePtr<T, D>& aX) { |
| 507 |
return aY != aX.get(); |
| 508 |
} |
| 509 |
|
| 510 |
template <typename T, class D> |
| 511 |
bool operator==(const UniquePtr<T, D>& aX, decltype(nullptr)) { |
| 512 |
return !aX; |
| 513 |
} |
| 514 |
|
| 515 |
template <typename T, class D> |
| 516 |
bool operator==(decltype(nullptr), const UniquePtr<T, D>& aX) { |
| 517 |
return !aX; |
| 518 |
} |
| 519 |
|
| 520 |
template <typename T, class D> |
| 521 |
bool operator!=(const UniquePtr<T, D>& aX, decltype(nullptr)) { |
| 522 |
return bool(aX); |
| 523 |
} |
| 524 |
|
| 525 |
template <typename T, class D> |
| 526 |
bool operator!=(decltype(nullptr), const UniquePtr<T, D>& aX) { |
| 527 |
return bool(aX); |
| 528 |
} |
| 529 |
|
| 530 |
// No operator<, operator>, operator<=, operator>= for now because simplicity. |
| 531 |
|
| 532 |
namespace detail { |
| 533 |
|
| 534 |
template <typename T> |
| 535 |
struct UniqueSelector { |
| 536 |
typedef UniquePtr<T> SingleObject; |
| 537 |
}; |
| 538 |
|
| 539 |
template <typename T> |
| 540 |
struct UniqueSelector<T[]> { |
| 541 |
typedef UniquePtr<T[]> UnknownBound; |
| 542 |
}; |
| 543 |
|
| 544 |
template <typename T, decltype(sizeof(int)) N> |
| 545 |
struct UniqueSelector<T[N]> { |
| 546 |
typedef UniquePtr<T[N]> KnownBound; |
| 547 |
}; |
| 548 |
|
| 549 |
} // namespace detail |
| 550 |
|
| 551 |
/** |
| 552 |
* MakeUnique is a helper function for allocating new'd objects and arrays, |
| 553 |
* returning a UniquePtr containing the resulting pointer. The semantics of |
| 554 |
* MakeUnique<Type>(...) are as follows. |
| 555 |
* |
| 556 |
* If Type is an array T[n]: |
| 557 |
* Disallowed, deleted, no overload for you! |
| 558 |
* If Type is an array T[]: |
| 559 |
* MakeUnique<T[]>(size_t) is the only valid overload. The pointer returned |
| 560 |
* is as if by |new T[n]()|, which value-initializes each element. (If T |
| 561 |
* isn't a class type, this will zero each element. If T is a class type, |
| 562 |
* then roughly speaking, each element will be constructed using its default |
| 563 |
* constructor. See C++11 [dcl.init]p7 for the full gory details.) |
| 564 |
* If Type is non-array T: |
| 565 |
* The arguments passed to MakeUnique<T>(...) are forwarded into a |
| 566 |
* |new T(...)| call, initializing the T as would happen if executing |
| 567 |
* |T(...)|. |
| 568 |
* |
| 569 |
* There are various benefits to using MakeUnique instead of |new| expressions. |
| 570 |
* |
| 571 |
* First, MakeUnique eliminates use of |new| from code entirely. If objects are |
| 572 |
* only created through UniquePtr, then (assuming all explicit release() calls |
| 573 |
* are safe, including transitively, and no type-safety casting funniness) |
| 574 |
* correctly maintained ownership of the UniquePtr guarantees no leaks are |
| 575 |
* possible. (This pays off best if a class is only ever created through a |
| 576 |
* factory method on the class, using a private constructor.) |
| 577 |
* |
| 578 |
* Second, initializing a UniquePtr using a |new| expression requires repeating |
| 579 |
* the name of the new'd type, whereas MakeUnique in concert with the |auto| |
| 580 |
* keyword names it only once: |
| 581 |
* |
| 582 |
* UniquePtr<char> ptr1(new char()); // repetitive |
| 583 |
* auto ptr2 = MakeUnique<char>(); // shorter |
| 584 |
* |
| 585 |
* Of course this assumes the reader understands the operation MakeUnique |
| 586 |
* performs. In the long run this is probably a reasonable assumption. In the |
| 587 |
* short run you'll have to use your judgment about what readers can be expected |
| 588 |
* to know, or to quickly look up. |
| 589 |
* |
| 590 |
* Third, a call to MakeUnique can be assigned directly to a UniquePtr. In |
| 591 |
* contrast you can't assign a pointer into a UniquePtr without using the |
| 592 |
* cumbersome reset(). |
| 593 |
* |
| 594 |
* UniquePtr<char> p; |
| 595 |
* p = new char; // ERROR |
| 596 |
* p.reset(new char); // works, but fugly |
| 597 |
* p = MakeUnique<char>(); // preferred |
| 598 |
* |
| 599 |
* (And third, although not relevant to Mozilla: MakeUnique is exception-safe. |
| 600 |
* An exception thrown after |new T| succeeds will leak that memory, unless the |
| 601 |
* pointer is assigned to an object that will manage its ownership. UniquePtr |
| 602 |
* ably serves this function.) |
| 603 |
*/ |
| 604 |
|
| 605 |
template <typename T, typename... Args> |
| 606 |
typename detail::UniqueSelector<T>::SingleObject MakeUnique(Args&&... aArgs) { |
| 607 |
return UniquePtr<T>(new T(std::forward<Args>(aArgs)...)); |
| 608 |
} |
| 609 |
|
| 610 |
template <typename T> |
| 611 |
typename detail::UniqueSelector<T>::UnknownBound MakeUnique( |
| 612 |
decltype(sizeof(int)) aN) { |
| 613 |
using ArrayType = std::remove_extent_t<T>; |
| 614 |
return UniquePtr<T>(new ArrayType[aN]()); |
| 615 |
} |
| 616 |
|
| 617 |
template <typename T, typename... Args> |
| 618 |
typename detail::UniqueSelector<T>::KnownBound MakeUnique(Args&&... aArgs) = |
| 619 |
delete; |
| 620 |
|
| 621 |
/** |
| 622 |
* WrapUnique is a helper function to transfer ownership from a raw pointer |
| 623 |
* into a UniquePtr<T>. It can only be used with a single non-array type. |
| 624 |
* |
| 625 |
* It is generally used this way: |
| 626 |
* |
| 627 |
* auto p = WrapUnique(new char); |
| 628 |
* |
| 629 |
* It can be used when MakeUnique is not usable, for example, when the |
| 630 |
* constructor you are using is private, or you want to use aggregate |
| 631 |
* initialization. |
| 632 |
*/ |
| 633 |
|
| 634 |
template <typename T> |
| 635 |
typename detail::UniqueSelector<T>::SingleObject WrapUnique(T* aPtr) { |
| 636 |
return UniquePtr<T>(aPtr); |
| 637 |
} |
| 638 |
|
| 639 |
} // namespace mozilla |
| 640 |
|
| 641 |
namespace std { |
| 642 |
|
| 643 |
template <typename T, class D> |
| 644 |
void swap(mozilla::UniquePtr<T, D>& aX, mozilla::UniquePtr<T, D>& aY) { |
| 645 |
aX.swap(aY); |
| 646 |
} |
| 647 |
|
| 648 |
} // namespace std |
| 649 |
|
| 650 |
/** |
| 651 |
TempPtrToSetter(UniquePtr<T>*) -> T**-ish |
| 652 |
TempPtrToSetter(std::unique_ptr<T>*) -> T**-ish |
| 653 |
|
| 654 |
Make a temporary class to support assigning to UniquePtr/unique_ptr via passing |
| 655 |
a pointer to the callee. |
| 656 |
|
| 657 |
Often, APIs will be shaped like this trivial example: |
| 658 |
``` |
| 659 |
nsresult Foo::NewChildBar(Bar** out) { |
| 660 |
if (!IsOk()) return NS_ERROR_FAILURE; |
| 661 |
*out = new Bar(this); |
| 662 |
return NS_OK; |
| 663 |
} |
| 664 |
``` |
| 665 |
|
| 666 |
In order to make this work with unique ptrs, it's often either risky or |
| 667 |
overwrought: |
| 668 |
``` |
| 669 |
Bar* bar = nullptr; |
| 670 |
const auto cleanup = MakeScopeExit([&]() { |
| 671 |
if (bar) { |
| 672 |
delete bar; |
| 673 |
} |
| 674 |
}); |
| 675 |
if (FAILED(foo->NewChildBar(&bar)) { |
| 676 |
// handle it |
| 677 |
} |
| 678 |
``` |
| 679 |
|
| 680 |
``` |
| 681 |
UniquePtr<Bar> bar; |
| 682 |
{ |
| 683 |
Bar* raw = nullptr; |
| 684 |
const auto res = foo->NewChildBar(&bar); |
| 685 |
bar.reset(raw); |
| 686 |
if (FAILED(res) { |
| 687 |
// handle it |
| 688 |
} |
| 689 |
} |
| 690 |
``` |
| 691 |
TempPtrToSettable is a shorthand for the latter approach, allowing something |
| 692 |
cleaner but also safe: |
| 693 |
|
| 694 |
``` |
| 695 |
UniquePtr<Bar> bar; |
| 696 |
if (FAILED(foo->NewChildBar(TempPtrToSetter(&bar))) { |
| 697 |
// handle it |
| 698 |
} |
| 699 |
``` |
| 700 |
*/ |
| 701 |
|
| 702 |
namespace mozilla { |
| 703 |
namespace detail { |
| 704 |
|
| 705 |
template <class T, class UniquePtrT> |
| 706 |
class MOZ_TEMPORARY_CLASS TempPtrToSetterT final { |
| 707 |
private: |
| 708 |
UniquePtrT* const mDest; |
| 709 |
T* mNewVal; |
| 710 |
|
| 711 |
public: |
| 712 |
explicit TempPtrToSetterT(UniquePtrT* dest) |
| 713 |
: mDest(dest), mNewVal(mDest->get()) {} |
| 714 |
|
| 715 |
operator T**() { return &mNewVal; } |
| 716 |
|
| 717 |
~TempPtrToSetterT() { |
| 718 |
if (mDest->get() != mNewVal) { |
| 719 |
mDest->reset(mNewVal); |
| 720 |
} |
| 721 |
} |
| 722 |
}; |
| 723 |
|
| 724 |
} // namespace detail |
| 725 |
|
| 726 |
template <class T, class Deleter> |
| 727 |
auto TempPtrToSetter(UniquePtr<T, Deleter>* const p) { |
| 728 |
return detail::TempPtrToSetterT<T, UniquePtr<T, Deleter>>{p}; |
| 729 |
} |
| 730 |
|
| 731 |
template <class T, class Deleter> |
| 732 |
auto TempPtrToSetter(std::unique_ptr<T, Deleter>* const p) { |
| 733 |
return detail::TempPtrToSetterT<T, std::unique_ptr<T, Deleter>>{p}; |
| 734 |
} |
| 735 |
|
| 736 |
} // namespace mozilla |
| 737 |
|
| 738 |
#endif /* mozilla_UniquePtr_h */ |