MeshKit
1.0
|
00001 #ifndef OBJECT_POOL_H 00002 #define OBJECT_POOL_H 00003 #include <assert.h> 00004 00005 #include <string> 00006 #include <vector> 00007 00008 #include <vector> 00009 using namespace std; 00010 00011 template <class T> 00012 class ObjectPool { 00013 struct Pool; 00014 public: 00015 00016 ObjectPool() { 00017 chunkSize = 1; 00018 } 00019 00020 virtual ~ObjectPool() { 00021 } 00022 00023 void setChunkSize(size_t n) { 00024 chunkSize = n; 00025 } 00026 00027 void reserve(size_t n) { 00028 Pool *p = new Pool(n); 00029 vpools.push_back(p); 00030 } 00031 00032 T *allocate() { 00033 Pool *p; 00034 if (!vpools.empty()) { 00035 p = vpools.back(); 00036 if (!p->is_filled()) return p->allocate(); 00037 } 00038 00039 // Resources exhausted, create new pool.. 00040 p = new Pool(chunkSize); 00041 vpools.push_back(p); 00042 00043 return p->allocate(); 00044 } 00045 00046 void release(T *obj) { 00047 } 00048 00049 int deleteAll() { 00050 for (size_t i = 0; i < vpools.size(); i++) { 00051 vpools[i]->deleteAll(); 00052 delete vpools[i]; 00053 } 00054 vpools.clear(); 00055 return 0; 00056 } 00057 private: 00058 size_t chunkSize; 00059 00060 struct Pool { 00061 00062 Pool(size_t n) { 00063 currpos = 0; 00064 capacity = n; 00065 objects = new T[capacity]; 00066 assert(objects != NULL); 00067 } 00068 00069 bool is_filled() const { 00070 return currpos == capacity; 00071 } 00072 00073 T * allocate() { 00074 return &objects[currpos++]; 00075 } 00076 00077 void deleteAll() { 00078 capacity = 0; 00079 currpos = 0; 00080 delete [] objects; 00081 objects = NULL; 00082 } 00083 00084 size_t capacity, currpos; 00085 T *objects; 00086 }; 00087 00088 std::vector<Pool*> vpools; 00089 }; 00090 00091 #endif