64,637
社区成员
发帖
与我相关
我的任务
分享
template <class T,int ALLOC_BLOCK_SIZE=10>
class CMemoryPool
{
public:
static void* operator new(std::size_t allocLength)
{
ASSERT(sizeof(T)==allocLength);
ASSERT(sizeof(T)>=sizeof(UCHAR*));
if(!mFreePointer)
allocBlock();
UCHAR *ReturnPointer=mFreePointer;
mFreePointer=*reinterpret_cast<UCHAR**>(ReturnPointer);
return ReturnPointer;
}
static void operator delete(void *deletePointer)
{
*reinterpret_cast<UCHAR**>(deletePointer)=mFreePointer;
mFreePointer=static_cast<UCHAR*>(deletePointer);
}
private:
static void allocBlock()
{
mFreePointer=new UCHAR[sizeof(T)*ALLOC_BLOCK_SIZE];
UCHAR **Current=reinterpret_cast<UCHAR**>(mFreePointer);
UCHAR *Next=mFreePointer;
for(int i=0;i<ALLOC_BLOCK_SIZE;i++)
{
Next+=sizeof(T);
*Current=Next;
Current=reinterpret_cast<UCHAR**>(Next);
}
*Current=0;
}private:
static UCHAR *mFreePointer;
protected:
~CMemoryPool() {delete mFreePointer;}
};
template<class T,int ALLOC_BLOCK_SIZE>
UCHAR *CMemoryPool<T,ALLOC_BLOCK_SIZE>::mFreePointer;