在C++中,频繁调用
new和
delete或
malloc与
free进行小对象分配会带来显著的性能开销,主要源于系统调用、内存碎片以及对齐处理。为解决这一问题,内存池(Memory Pool)结合自定义分配器(Custom Allocator)是一种高效方案。本文将带你从零实现一个简单的C++内存池,并开发配套的STL兼容分配器。 内存池基本原理
内存池预先分配一大块连续内存,按固定大小切分为多个槽(slot),每次分配只需返回一个空闲槽,释放时将其重新标记为空闲。这种方式避免了操作系统频繁介入,极大提升小对象分配效率。
核心特点:
- 固定块大小,适合频繁分配/释放同类对象
- 分配与释放时间复杂度为 O(1)
- 减少内存碎片,提升缓存局部性
以下是一个支持固定大小对象的内存池类:
// MemoryPool.hclass MemoryPool {
private:
struct Block {
Block* next;
};
Block* freeList;
char* memory;
size_t blockSize;
size_t poolSize;
public:
MemoryPool(size_t count, size_t size)
: blockSize((size + alignof(Block) - 1) / alignof(Block) * alignof(Block)),
poolSize(count), freeList(nullptr) {
memory = new char[blockSize * count];
initializePool();
}
~MemoryPool() {
delete[] memory;
}
void* allocate() {
if (!freeList) return nullptr;
Block* block = freeList;
freeList = freeList->next;
return block;
}
void deallocate(void* p) {
Block* block = static_cast<Block*>(p);
block->next = freeList;
freeList = block;
}
private:
void initializePool() {
for (size_t i = 0; i < poolSize; ++i) {
Block* block = reinterpret_cast<Block*>(memory + i * blockSize);
block->next = freeList;
freeList = block;
}
}
};
要让STL容器(如
std::vector、
std::list)使用内存池,需实现符合Allocator要求的模板类。 // PoolAllocator.h
template <typename T, size_t N = 1024>
class PoolAllocator {
public:
using value_type = T;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
template <typename U>
struct rebind {
using other = PoolAllocator<U, N>;
};
PoolAllocator() {
if (!pool) {
pool = new MemoryPool(N, sizeof(T));
}
}
~PoolAllocator() = default;
template <typename U>
PoolAllocator(const PoolAllocator<U, N>&) {}
pointer allocate(size_type n) {
if (n == 1) {
return static_cast<pointer>(pool->allocate());
}
throw std::bad_alloc();
}
void deallocate(pointer p, size_type n) {
if (n == 1) {
pool->deallocate(p);
}
}
template <typename U, typename... Args>
void construct(U* p, Args&&... args) {
new(p) U(std::forward<Args>(args)...);
}
void destroy(pointer p) {
p->~T();
}
static MemoryPool* pool;
};
template <typename T, size_t N>
MemoryPool* PoolAllocator<T, N>::pool = nullptr;
将自定义分配器用于
std::vector:
#include <vector>
struct Point {
float x, y;
Point(float x = 0, float y = 0) : x(x), y(y) {}
};
int main() {
using PoolVec = std::vector<Point, PoolAllocator<Point, 100>>;
PoolVec points;
points.emplace_back(1.0f, 2.0f);
points.emplace_back(3.0f, 4.0f);
// 所有Point对象由内存池分配
return 0;
}
注意:此分配器仅支持单对象分配(n=1),不适用于需要连续大块内存的场景。
基本上就这些。通过内存池+自定义分配器,你可以显著优化特定场景下的内存性能。关键是理解分配模式,合理设计块大小和池容量。不复杂但容易忽略细节,比如对齐和静态池管理。实际项目中可考虑使用
boost::pool或进一步支持多尺寸池。
以上就是C++内存池实现 自定义分配器开发指南的详细内容,更多请关注知识资源分享宝库其它相关文章!
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。