| 1 | // -*- C++ -*- |
| 2 | |
| 3 | /* |
| 4 | |
| 5 | Heap Layers: An Extensible Memory Allocation Infrastructure |
| 6 | |
| 7 | Copyright (C) 2000-2020 by Emery Berger |
| 8 | http://www.emeryberger.com |
| 9 | [email protected] |
| 10 | |
| 11 | Heap Layers is distributed under the terms of the Apache 2.0 license. |
| 12 | |
| 13 | You may obtain a copy of the License at |
| 14 | http://www.apache.org/licenses/LICENSE-2.0 |
| 15 | |
| 16 | */ |
| 17 | |
| 18 | #ifndef HL_EXCEPTIONHEAP_H |
| 19 | #define HL_EXCEPTIONHEAP_H |
| 20 | |
| 21 | #include <new> |
| 22 | |
| 23 | // explicit throw lists are deprecated in C++11 and higher, and GCC |
| 24 | // complains about them |
| 25 | #if __cplusplus >= 201103L |
| 26 | #define HL_THROW_BAD_ALLOC |
| 27 | #else |
| 28 | class std::bad_alloc; |
| 29 | #define HL_THROW_BAD_ALLOC throw (std::bad_alloc) |
| 30 | #endif |
| 31 | |
| 32 | |
| 33 | namespace HL { |
| 34 | |
| 35 | template <class Super> |
| 36 | class ExceptionHeap : public Super { |
| 37 | public: |
| 38 | inline void * malloc (size_t sz) HL_THROW_BAD_ALLOC { |
| 39 | void * ptr = Super::malloc (sz); |
| 40 | if (ptr == NULL) { |
| 41 | throw std::bad_alloc(); |
| 42 | } |
| 43 | return ptr; |
| 44 | } |
| 45 | }; |
| 46 | |
| 47 | |
| 48 | template <class Super> |
| 49 | class CatchExceptionHeap : public Super { |
| 50 | public: |
| 51 | inline void * malloc (size_t sz) { |
| 52 | void * ptr; |
| 53 | try { |
| 54 | ptr = Super::malloc (sz); |
| 55 | } catch (std::bad_alloc) { |
| 56 | ptr = NULL; |
| 57 | } |
| 58 | return ptr; |
| 59 | } |
| 60 | }; |
| 61 | |
| 62 | } |
| 63 | |
| 64 | #endif |