内存管理类

来源:互联网 发布:天文望远镜知乎 编辑:程序博客网 时间:2024/06/05 05:59
#pragma once#ifndef GAME_MEMORYPOOL_H#define GAME_MEMORYPOOL_H// 类存管理template <class T, int ALLOC_BLOCK_SIZE = 50>class game_memorypool{private:static unsigned char *mFreePointer;protected:~game_memorypool(void){}public:// 重载newstatic void* operator new(std::size_t allocLength){assert(sizeof(T)==allocLength);assert(sizeof(T)>=sizeof(unsigned char*));if (!mFreePointer){allocBlock();}unsigned char *ReturnPointer = mFreePointer;mFreePointer = *reinterpret_cast<unsigned char**>(ReturnPointer);return ReturnPointer;}// 内存分配static void allocBlock(void){{mFreePointer = new unsigned char[sizeof(T)*ALLOC_BLOCK_SIZE];unsigned char **Current = reinterpret_cast<unsigned char **>(mFreePointer);unsigned char *Next = mFreePointer;for (int i=0; i<ALLOC_BLOCK_SIZE-1; ++i){Next+=sizeof(T);*Current = Next;Current = reinterpret_cast<unsigned char**>(Next);}*Current = 0;}}// 重载deletestatic void operator delete(void* deletePointer){*reinterpret_cast<unsigned char**>(deletePointer) = mFreePointer;mFreePointer = static_cast<unsigned char*>(deletePointer);}};template <class T, int ALLOC_BLOCK_SIZE>unsigned char* game_memorypool<T, ALLOC_BLOCK_SIZE>::mFreePointer = NULL;#endif



class game_input:public game_memorypool<game_input>
{
 //............
}

原创粉丝点击