00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 #ifndef __OBJPOOL_H__
00020 #define __OBJPOOL_H__
00021
00028 #define DECLARE_OBJECT_POOL(name,type) \
00029 class name : private csObjectPool { \
00030 private: \
00031 virtual void* CreateItem () \
00032 { return new type (); } \
00033 virtual void FreeItem (void* o) \
00034 { type *obj = (type*)o; delete obj; } \
00035 public: \
00036 type *Allocate () \
00037 { return csObjectPool::Allocate (); } \
00038 void Free (type *o) \
00039 { csObjectPool::Free (o); } \
00040 };
00041
00043 class csObjectPool
00044 {
00045 private:
00046 csSome *Objects;
00047 int Num, Max;
00048
00049 public:
00050 virtual void* CreateItem () = 0;
00051 virtual void FreeItem (void*) = 0;
00052
00053 csObjectPool ()
00054 {
00055 Objects = new csSome [16];
00056 Num = 0;
00057 Max = 16;
00058 }
00059 ~csObjectPool ()
00060 {
00061 int i;
00062 for (i=0; i<Num; i++)
00063 FreeItem (Objects[Num]);
00064 delete[] Objects;
00065 }
00066 void *Allocate ()
00067 {
00068 if (Num > 0) {
00069 Num--;
00070 return Objects [Num];
00071 } else {
00072 return CreateItem ();
00073 }
00074 }
00075 void Free (void* o) {
00076 if (Num == Max) {
00077 csSome *old = Objects;
00078 Objects = new csSome [Max + 16];
00079 memcpy (Objects, old, sizeof (csSome) * Max);
00080 delete[] old;
00081 Max += 16;
00082 }
00083 Objects [Num] = o;
00084 Num++;
00085 }
00086 };
00087
00088 #endif // __OBJPOOL_H__