Unk*_*own 6 c++ memory memory-management
对基于堆栈的分配器的任何建议?(除了建议使用私人/公共成员的课程)
struct Heap
{
void* heap_start;
void* heap_end;
size_t max_end;
Heap(size_t size)
{
heap_start = malloc(size);
heap_end = heap_start;
max_end = size + (size_t) heap_start;
}
~Heap()
{
::free(heap_start);
}
void* allocate(size_t bytes)
{
size_t new_end = ((size_t) heap_end) + bytes;
if( new_end > max_end )
throw std::bad_alloc();
void* output = heap_end;
heap_end = (void*) new_end;
return output;
}
}
Run Code Online (Sandbox Code Playgroud)