1 // -*- C++ -*- 2 3 /* 4 5 Heap Layers: An Extensible Memory Allocation Infrastructure 6 7 Copyright (C) 2000-2012 by Emery Berger 8 http://www.cs.umass.edu/~emery 9 emery@cs.umass.edu 10 11 This program is free software; you can redistribute it and/or modify 12 it under the terms of the GNU General Public License as published by 13 the Free Software Foundation; either version 2 of the License, or 14 (at your option) any later version. 15 16 This program is distributed in the hope that it will be useful, 17 but WITHOUT ANY WARRANTY; without even the implied warranty of 18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 GNU General Public License for more details. 20 21 You should have received a copy of the GNU General Public License 22 along with this program; if not, write to the Free Software 23 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 24 25 */ 26 27 #ifndef HL_EXCEPTIONHEAP_H 28 #define HL_EXCEPTIONHEAP_H 29 30 #include <new> 31 32 // explicit throw lists are deprecated in C++11 and higher, and GCC 33 // complains about them 34 #if __cplusplus >= 201103L 35 #define HL_THROW_BAD_ALLOC 36 #else 37 class std::bad_alloc; 38 #define HL_THROW_BAD_ALLOC throw (std::bad_alloc) 39 #endif 40 41 42 namespace HL { 43 44 template <class Super> 45 class ExceptionHeap : public Super { 46 public: malloc(size_t sz)47 inline void * malloc (size_t sz) HL_THROW_BAD_ALLOC { 48 void * ptr = Super::malloc (sz); 49 if (ptr == NULL) { 50 throw new std::bad_alloc; 51 } 52 return ptr; 53 } 54 }; 55 56 57 template <class Super> 58 class CatchExceptionHeap : public Super { 59 public: malloc(size_t sz)60 inline void * malloc (size_t sz) { 61 void * ptr; 62 try { 63 ptr = Super::malloc (sz); 64 } catch (std::bad_alloc) { 65 ptr = NULL; 66 } 67 return ptr; 68 } 69 }; 70 71 } 72 73 #endif 74