UniquePtr.h 23 KB

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