今天的微博有人讨论到对象池,我想到之前项目的实现,应该用模板来实现啊,唉,还是被前人的想法给框定了,不过实现一个特别简单,花了几分钟写了个:
#include <queue> #include <cstdio> using namespace std; const int DefaultPoolSize = 1024; template <class T> class ObejctPool{ private: queue<T*> m_OriBlock; queue<T*> m_ObjectBlock; const int m_DefaultBlockSize; public: ~ObejctPool(){ while (!m_OriBlock.empty()){ T* pBlock = m_OriBlock.front(); delete []pBlock; m_OriBlock.pop(); } } ObejctPool(int blockSize = DefaultPoolSize):m_DefaultBlockSize(blockSize){ } T* GetObject(){ if (true == m_ObjectBlock.empty()){ T* pNewObject = new T[m_DefaultBlockSize]; m_OriBlock.push(pNewObject); for (int i = 0; i < m_DefaultBlockSize; ++i){ m_ObjectBlock.push(pNewObject+i); } } T* pGetObject = m_ObjectBlock.front(); m_ObjectBlock.pop(); return pGetObject; } void ReleaseObejct(T* pObject){ if (0 == pObject){ return; } m_ObjectBlock.push(pObject); } }; int main(){ ObejctPool<int> obj; int* p = obj.GetObject(); *p = 1; printf("get:%d\n", *p); obj.ReleaseObejct(p); }
原文地址:http://blog.csdn.net/boyxiaolong/article/details/35614979