FEI Version of the Day
fei_Pool.hpp
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 _fei_Pool_hpp_
00010 #define _fei_Pool_hpp_
00011 
00012 #include "fei_macros.hpp"
00013 
00014 #include <cstdlib>
00015 
00016 #ifndef FEI_ALLOC_CHUNK_SIZE_K
00017 #define FEI_ALLOC_CHUNK_SIZE_K 512
00018 #endif
00019 
00020 //The macro FEI_ALLOC_CHUNK_SIZE_K determines the number
00021 //of kilobytes that each internally-allocated chunk of memory will
00022 //occupy. The fei_Pool object will then dispense "sub-chunks"
00023 //of memory having size determined by the argument to the class
00024 //constructor.
00025 
00026 class fei_Pool {
00027  public:
00028   fei_Pool(unsigned int n); // n is the size of elements
00029   ~fei_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 = FEI_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   fei_Pool(const fei_Pool&);//private copy constructor
00050   fei_Pool& operator=(const fei_Pool&);//private assignment operator
00051   void grow(); //make pool larger
00052 };
00053 
00054 inline void* fei_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 fei_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 #endif
00072 
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Friends