重载删除和检索大小?

mok*_*oka 5 c++ memory-management

我目前正在用C++编写一个小的自定义内存分配器,并希望将它与运算符重载new/ 一起使用delete.无论如何,我的内存分配器基本上检查请求的内存是否超过某个阈值,如果是,则使用malloc分配请求的内存块.否则,内存将由一些fixedPool分配器提供.这通常有效,但对于我的释放函数看起来像这样:

void MemoryManager::deallocate(void * _ptr, size_t _size){
    if(_size > heapThreshold)
        deallocHeap(_ptr);
    else 
        deallocFixedPool(_ptr, _size);
}
Run Code Online (Sandbox Code Playgroud)

所以我需要提供指向的块的大小,从正确的位置解除分配.

现在的问题是delete关键字没有提供任何关于已删除块的大小的提示,所以我需要这样的东西:

void operator delete(void * _ptr, size_t _size){ 
    MemoryManager::deallocate(_ptr, _size); 
}
Run Code Online (Sandbox Code Playgroud)

但据我所知,没有办法确定删除操作符内的大小.-如果我想保持现在的状态,我是否必须自己保存内存块的大小?

Eva*_*ran 5

分配比需要更多的内存并在那里存储大小信息.这就是你的系统分配器可能已经做的事情.像这样的东西(为了简单起见用malloc演示):

void *allocate(size_t size) {
    size_t *p = malloc(size + sizeof(size_t));
    p[0] = size;           // store the size in the first few bytes
    return (void*)(&p[1]); // return the memory just after the size we stored
}

void deallocate(void *ptr) {
    size_t *p = (size_t*)ptr; // make the pointer the right type
    size_t size = p[-1];      // get the data we stored at the beginning of this block

    // do what you need with size here...

    void *p2 = (void*)(&p[-1]); // get a pointer to the memory we originally really allocated
    free(p2);                   // free it
}
Run Code Online (Sandbox Code Playgroud)