re: 大内存申请和释放的类 commons 2005-02-05 23:08
class CMemoryManager
{
public:
CMemoryManager()
{
memory = NULL;
size = 0;
}
CMemoryManager(size_t size)
{
this -> size = size;
memory = VirtualAlloc(NULL,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
if ( memory == NULL )
{
throw Exception("Memory malloc failed!");
}
}
CMemoryManager(const CMemoryManager &another)
{
if ( this -> memory != NULL )
{
destroyMemory();
}
this -> size = another.size;
this -> memory = VirtualAlloc(NULL,this -> size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
if ( this -> memory == NULL )
{
throw Exception("Memory malloc failed!");
}
CopyMemory(this -> memory,another.getMemory(),this->size);
}
PVOID applyMemory(size_t size) //申请内存
{
if ( memory != NULL ) //如果内存不为空,先释放内存
{
VirtualFree(memory,this -> size,MEM_RELEASE);
memory = NULL;
this -> size = 0;
}
this -> size = size;
//分配内存空间
memory = VirtualAlloc(NULL,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
if ( memory == NULL )
{
throw Exception("Memory malloc failed!");
}
return this -> memory ;
}
void destroyMemory() //释放内存
{
if ( memory != NULL ) //内存不为NULL
{
VirtualFree(memory,size,MEM_RELEASE); //释放申请的内存空间
memory = NULL; //内存指针初始化
size = 0; //大小初始化
}
}
PVOID getMemory()
{
return this -> memory; //返回申请的内存空间
}
size_t getMemorySize()
{
return this -> size; //得到申请的内存的大小
}
~CMemoryManager() //析构函数
{
destroyMemory(); //释放内存
}
private:
PVOID memory;
size_t size;
};