00001 /*************************************************************************** 00002 * 00003 * $Id: StMemoryPool.hh,v 1.2 1999/11/18 17:55:46 ullrich Exp $ 00004 * 00005 * Author: Thomas Ullrich, Nov 1999 00006 *************************************************************************** 00007 * 00008 * Description: 00009 * 00010 * Idea taken from: 00011 * B. Stroustrup, The C++ Programming Language, 3ed edition, 00012 * Chapter 19 (page 570) 00013 * 00014 * Should be used if a large number of small objects has to be 00015 * frequently allocated from heap. It is much more efficient and 00016 * faster than the standard new/delete operators. 00017 * Add to the referring class X the following lines: 00018 * 00019 * class X { 00020 * public: 00021 * void* operator new(size_t) { return mPool.alloc(); } 00022 * void operator delete(void* p) { mPool.free(p); } 00023 * ... 00024 * privat: 00025 * static StMemoryPool mPool; 00026 * ... 00027 * } 00028 * 00029 * StMemoryPool X::mPool(sizeof(X)); 00030 * 00031 * Note that the class is optimized for speed and compactness 00032 * not for readability. Only single objects may be created, 00033 * i.e, new X[100] will not work; however, in these cases the 00034 * default operators new/delete will be called. 00035 * 00036 *************************************************************************** 00037 * 00038 * $Log: StMemoryPool.hh,v $ 00039 * Revision 1.2 1999/11/18 17:55:46 ullrich 00040 * Corrected reference to Stroustrup. 00041 * 00042 * Revision 1.1 1999/11/09 19:29:13 ullrich 00043 * Initial Revision 00044 * 00045 **************************************************************************/ 00046 #ifndef ST_MEMORY_POOL_HH 00047 #define ST_MEMORY_POOL_HH 00048 00049 00050 class StMemoryPool { 00051 public: 00052 StMemoryPool(unsigned int n); 00053 ~StMemoryPool(); 00054 00055 void* alloc(); 00056 void free(void*); 00057 00058 private: 00059 StMemoryPool(); 00060 StMemoryPool(StMemoryPool&); 00061 void operator= (StMemoryPool&); 00062 void grow(); 00063 00064 struct Link { Link* next; }; 00065 struct Chunk { 00066 enum {size = 16*1024-16}; 00067 Chunk* next; 00068 char mem[size]; 00069 }; 00070 Chunk *chunks; 00071 Link* head; 00072 const unsigned int esize; 00073 }; 00074 00075 00076 inline void* 00077 StMemoryPool::alloc() 00078 { 00079 if (head == 0) grow(); 00080 Link* p = head; 00081 head = p->next; 00082 return p; 00083 } 00084 00085 inline void 00086 StMemoryPool::free(void* b) 00087 { 00088 if (b != 0) { 00089 Link* p = static_cast<Link*>(b); 00090 p->next = head; 00091 head = p; 00092 } 00093 } 00094 #endif
1.5.9