定制化内存池:小对象分配器
实现固定大小块的自由链表内存池,避免malloc碎片和锁竞争,用于高频创建/销毁的小对象场景。 · 难度:入门 · +10XP
定制化内存池:小对象分配器
通用malloc在小对象场景下效率低且碎片多。本教程实现一个模板化的内存池,内部维护固定大小块的自由链表,分配O(1),释放O(1)且无锁(单线程版)。讲解内存对齐处理、块头使用、以及如何通过placement new构造对象。最后对比与std::allocator的性能差异,展示在节点容器中的优势。
template<typename T, size_t BlockSize = 4096>
class PoolAllocator {
union Node { Node* next; }; // 空闲链表
Node* free_head = nullptr;
public:
T* allocate() {
if(!free_head) expand();
auto p = free_head;
free_head = free_head->next;
return reinterpret_cast<T*>(p);
}
void deallocate(T* p) {
auto n = reinterpret_cast<Node*>(p);
n->next = free_head;
free_head = n;
}
};