|
Sierra Toolkit
Version of the Day
|
00001 /*--------------------------------------------------------------------*/ 00002 /* Copyright 2005 Sandia Corporation. */ 00003 /* Under the terms of Contract DE-AC04-94AL85000, there is a */ 00004 /* non-exclusive license for use of this work by or on behalf */ 00005 /* of the U.S. Government. Export of this program may require */ 00006 /* a license from the United States Government. */ 00007 /*--------------------------------------------------------------------*/ 00008 00009 #ifndef _stk_util_util_Pool_hpp_ 00010 #define _stk_util_util_Pool_hpp_ 00011 00012 #include <cstdlib> 00013 00014 #ifndef STK_UTIL_POOL_ALLOC_CHUNK_SIZE_K 00015 #define STK_UTIL_POOL_ALLOC_CHUNK_SIZE_K 512 00016 #endif 00017 00018 //The macro STK_UTIL_POOL_ALLOC_CHUNK_SIZE_K determines the number 00019 //of kilobytes that each internally-allocated chunk of memory will 00020 //occupy. The Pool object will then dispense "sub-chunks" 00021 //of memory having size determined by the argument to the class 00022 //constructor. 00023 00024 namespace stk_classic { 00025 namespace util { 00026 class Pool { 00027 public: 00028 Pool(unsigned int nbytes); // nbytes is the size of elements 00029 ~Pool(); 00030 00031 void* alloc(); //allocate one element 00032 void free(void* b); //put an element back into the pool 00033 struct Link { Link* next; }; 00034 00035 private: 00036 struct Chunk { 00037 //Stroustrup's comment: 00038 //slightly less than specified K so that a chunk will fit in 00039 //allocation area first to get stringent alignment 00040 enum { size = STK_UTIL_POOL_ALLOC_CHUNK_SIZE_K*1024-16 }; 00041 char mem[size]; 00042 Chunk* next; 00043 }; 00044 00045 Chunk* chunks; 00046 const unsigned int esize; 00047 Link* head; 00048 00049 Pool(const Pool&);//private copy constructor 00050 Pool& operator=(const Pool&);//private assignment operator 00051 void grow(); //make pool larger 00052 }; 00053 00054 inline void* Pool::alloc() 00055 { 00056 if (head == NULL) { 00057 grow(); 00058 } 00059 Link* p = head; //return first element 00060 head = p->next; 00061 return p; 00062 } 00063 00064 inline void Pool::free(void* b) 00065 { 00066 Link* p = static_cast<Link*>(b); 00067 p->next = head; //put b back as first element 00068 head = p; 00069 } 00070 00071 }//namespace util 00072 }//namespace stk_classic 00073 00074 #endif 00075