UniquePtrExtensions.h 1.5 KB

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