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 CS_DECLARE_OBJECT_POOL(name,type) \
00029 class name : protected 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 virtual ~name () \
00037 { for (int i=0; i<Num; i++) FreeItem (Objects[i]); } \
00038 type *Alloc () \
00039 { return (type*)csObjectPool::Alloc (); } \
00040 void Free (type *o) \
00041 { csObjectPool::Free (o); } \
00042 };
00043
00045 class csObjectPool
00046 {
00047 protected:
00048 csSome *Objects;
00049 int Num, Max;
00050
00051 public:
00052 virtual void* CreateItem () = 0;
00053 virtual void FreeItem (void*) = 0;
00054
00055 csObjectPool ()
00056 {
00057 Objects = new csSome [16];
00058 Num = 0;
00059 Max = 16;
00060 }
00061 virtual ~csObjectPool ()
00062 {
00063 delete[] Objects;
00064 }
00065 void *Alloc ()
00066 {
00067 if (Num > 0) {
00068 Num--;
00069 return Objects [Num];
00070 } else {
00071 return CreateItem ();
00072 }
00073 }
00074 void Free (void* o) {
00075 if (Num == Max) {
00076 csSome *old = Objects;
00077 Objects = new csSome [Max + 16];
00078 memcpy (Objects, old, sizeof (csSome) * Max);
00079 delete[] old;
00080 Max += 16;
00081 }
00082 Objects [Num] = o;
00083 Num++;
00084 }
00085 };
00086
00087 #endif // __OBJPOOL_H__