Line data Source code
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>
22 : typename detail::UniqueSelector<T>::SingleObject
23 : MakeUniqueFallible(Args&&... aArgs)
24 : {
25 : return UniquePtr<T>(new (fallible) T(Forward<Args>(aArgs)...));
26 : }
27 :
28 : template<typename T>
29 : typename detail::UniqueSelector<T>::UnknownBound
30 136 : MakeUniqueFallible(decltype(sizeof(int)) aN)
31 : {
32 : typedef typename RemoveExtent<T>::Type ArrayType;
33 272 : return UniquePtr<T>(new (fallible) ArrayType[aN]());
34 : }
35 :
36 : template<typename T, typename... Args>
37 : typename detail::UniqueSelector<T>::KnownBound
38 : MakeUniqueFallible(Args&&... aArgs) = delete;
39 :
40 : namespace detail {
41 :
42 : template<typename T>
43 : struct FreePolicy
44 : {
45 7 : void operator()(const void* ptr) {
46 7 : free(const_cast<void*>(ptr));
47 7 : }
48 : };
49 :
50 : } // namespace detail
51 :
52 : template<typename T>
53 : using UniqueFreePtr = UniquePtr<T, detail::FreePolicy<T>>;
54 :
55 : } // namespace mozilla
56 :
57 : #endif // mozilla_UniquePtrExtensions_h
|