我正在设计一个自定义内存分配器,它管理一个包含固定数量项目的大块池。
using T = ItemType;
struct Block {
char data[M*sizeof(T)]; // M is tunable, power of two or else
int i {0};
Freelist freelist;
// ... other data field
}
// Pool collects a number of pooled blocks
struct Pool {
std::list<Block> blocks;
// other data field
}
将从可用块中allocate
分配一项未初始化的内存。由于申请,我allocate
需要一次处理一件。项目的字节大小为sizeof(T)
。
T* allocate() {
Block b* = pool.get_one_block();
int idx = b->get_free_index();
return reinterpret_cast<T*>(b->data) + idx;
}
deallocate
获取一个项目指针并将其ptr
回收到分配器。在进行任何内部处理之前,我们需要知道项目的block
. 如何在不要求T
在其原始块中包含其他卫星指针的情况下执行此操作?
void deallocate(T* ptr) {
Block* b = how_to_get_the_block_of_ptr(); // <-- is there any faster way to do so?
b->add_free_list(ptr);
// other internal processing
}
我听说在设计内存分配器时有一些按位技巧以及对齐的内存分配来检索指针块。帮助需要。