| 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_PERCLASSHEAP_H |
| 19 | #define HL_PERCLASSHEAP_H |
| 20 | |
| 21 | #include <new> |
| 22 | |
| 23 | /** |
| 24 | * @class PerClassHeap |
| 25 | * @brief Enable the use of one heap for all class memory allocation. |
| 26 | * |
| 27 | * This class contains one instance of the SuperHeap argument. The |
| 28 | * example below shows how to make a subclass of Foo that uses a |
| 29 | * FreelistHeap to manage its memory, overloading operators new and |
| 30 | * delete. |
| 31 | * |
| 32 | * <TT> |
| 33 | * class NewFoo : public Foo, PerClassHeap<FreelistHeap<MallocHeap> > {}; |
| 34 | * </TT> |
| 35 | */ |
| 36 | |
| 37 | namespace HL { |
| 38 | |
| 39 | template <class SuperHeap> |
| 40 | class PerClassHeap { |
| 41 | public: |
| 42 | inline void * operator new (size_t sz) { |
| 43 | return getHeap()->malloc (sz); |
| 44 | } |
| 45 | inline void operator delete (void * ptr) { |
| 46 | getHeap()->free (ptr); |
| 47 | } |
| 48 | inline void * operator new[] (size_t sz) { |
| 49 | return getHeap()->malloc (sz); |
| 50 | } |
| 51 | inline void operator delete[] (void * ptr) { |
| 52 | getHeap()->free (ptr); |
| 53 | } |
| 54 | // For some reason, g++ needs placement new to be overridden |
| 55 | // as well, at least in conjunction with use of the STL. |
| 56 | // Otherwise, this should be superfluous. |
| 57 | inline void * operator new (size_t, void * p) { return p; } |
| 58 | inline void * operator new[] (size_t, void * p) { return p; } |
| 59 | |
| 60 | private: |
| 61 | inline static SuperHeap * getHeap (void) { |
| 62 | static SuperHeap theHeap; |
| 63 | return &theHeap; |
| 64 | } |
| 65 | }; |
| 66 | |
| 67 | } |
| 68 | |
| 69 | #endif |