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 /* Useful extensions to UniquePtr. */ 8 9 #ifndef mozilla_UniquePtrExtensions_h 10 #define mozilla_UniquePtrExtensions_h 11 12 #include "mozilla/fallible.h" 13 #include "mozilla/UniquePtr.h" 14 15 namespace mozilla { 16 17 /** 18 * MakeUniqueFallible works exactly like MakeUnique, except that the memory 19 * allocation performed is done fallibly, i.e. it can return nullptr. 20 */ 21 template <typename T, typename... Args> MakeUniqueFallible(Args &&...aArgs)22typename detail::UniqueSelector<T>::SingleObject MakeUniqueFallible( 23 Args&&... aArgs) { 24 return UniquePtr<T>(new (fallible) T(Forward<Args>(aArgs)...)); 25 } 26 27 template <typename T> MakeUniqueFallible(decltype (sizeof (int))aN)28typename detail::UniqueSelector<T>::UnknownBound MakeUniqueFallible( 29 decltype(sizeof(int)) aN) { 30 typedef typename RemoveExtent<T>::Type ArrayType; 31 return UniquePtr<T>(new (fallible) ArrayType[aN]()); 32 } 33 34 template <typename T, typename... Args> 35 typename detail::UniqueSelector<T>::KnownBound MakeUniqueFallible( 36 Args&&... aArgs) = delete; 37 38 namespace detail { 39 40 template <typename T> 41 struct FreePolicy { operatorFreePolicy42 void operator()(const void* ptr) { free(const_cast<void*>(ptr)); } 43 }; 44 45 } // namespace detail 46 47 template <typename T> 48 using UniqueFreePtr = UniquePtr<T, detail::FreePolicy<T>>; 49 50 } // namespace mozilla 51 52 #endif // mozilla_UniquePtrExtensions_h 53