This commit is contained in:
2021-04-07 16:26:42 +08:00
2 changed files with 33 additions and 21 deletions

View File

@@ -18,6 +18,8 @@ namespace hgl
uint64 alloc_unit_size; ///<分配单位长度(分配长度必须为此值的整倍数)
uint64 alloc_size; ///<实际分配数据长度
virtual bool Alloc ()=0; ///<分配指定空间的数据
public:
virtual const uint64 GetSize ()const{return data_size;} ///<获取所需求的内存大小
@@ -49,13 +51,17 @@ namespace hgl
AbstractMemoryAllocator();
virtual ~AbstractMemoryAllocator()=default;
virtual bool Alloc (const uint64 size)=0; ///<分配指定空间的数据
bool Alloc (const uint64); ///<分配指定长度的空间
virtual void Free ()=0; ///<释放数据空间
virtual void Clear (){data_size=0;}
};//class AbstractMemoryAllocator
class MemoryAllocator:public AbstractMemoryAllocator
{
protected:
virtual bool Alloc() override;
public:
virtual const bool CanRealloc()const override{return true;}
@@ -64,8 +70,6 @@ namespace hgl
using AbstractMemoryAllocator::AbstractMemoryAllocator;
virtual ~MemoryAllocator();
virtual bool Alloc(const uint64 size);
virtual void Free() override;
};//class MemoryAllocator:public AbstractMemoryAllocator
}//namespace hgl

View File

@@ -40,33 +40,41 @@ namespace hgl
return result;
}
bool AbstractMemoryAllocator::Alloc(const uint64 size)
{
if(size<=0)return(false);
if(memory_block)
{
if(size<=data_size)return(true);
if(size<=alloc_size)
{
data_size=size;
return(true);
}
}
alloc_size=ComputeAllocSize(size);
if(!Alloc())
return(false);
data_size=size;
return(true);
}
MemoryAllocator::~MemoryAllocator()
{
Free();
}
bool MemoryAllocator::Alloc(const uint64 size)
bool MemoryAllocator::Alloc()
{
if(size<=0)return(false);
if(size<=data_size)return(true);
if(size<=alloc_size)
{
data_size=size;
return(true);
}
alloc_size=ComputeAllocSize(size);
memory_block=hgl_align_realloc(memory_block,alloc_size,alloc_unit_size); //hgl_align_realloc支持传入空的memory_block所以无需判断malloc/realloc
if(!memory_block)
return(false);
data_size=size;
return(memory_block);
return memory_block;
}
void MemoryAllocator::Free()