分配固定大小对象的内存池

//下面的代码思想取自efficient c++
1 // 2 //可分为:1.内存池本身的创建和删除 3 //2.内存池中空闲内存的维护 4 //两个部分区分开,逻辑就清晰了。 5 //by wangpei 2015.1.4 6 / 7 template 8 class MemoryPool{ 9 public: 10MemoryPool(size_t size = EXSIZE); 11~MemoryPool(); 12inline void* alloca(size_t size); 13inline void free(void *element); 14 private: 15enum {EXSIZE = 32}; 16MemoryPool *next; 17void expand(size_t s = EXSIZE); 18 }; 19 template 20 MemoryPool::MemoryPool(size_t size) 21 { 22expand(size); 23 } 24 25 template 26 MemoryPool::~MemoryPool() 27 { 28MemoryPool * ptr; 29while (next){ 30ptr = next->next; 31delete[] freeNode; //指针指向了正确的初始位置,就能够正确的释放空间 32de++; 33next = ptr; 34} 35 } 36 37 template 38 inline void* MemoryPool::alloca(size_t size) 39 { 40if (next == 0) 41expland(); 42MemoryPool* currentFree = next; 43next = next->next; 44return currentFree; 45 } 46 47 template 48 inline void MemoryPool::free(void *element) 49 { 50MemoryPool* head = static_cast* >(doomed); //注意此处的链表维护,不能让链表断开了 51head->next = next; 52next = head; 53 } 54 55 template 56 void MemoryPool::expand(size_t s) 57 { 58const size_t s = (sizeof(MemoryPool*) >= sizeof(T)) ? sizeof(MemoryPool*) : sizeof(T); //这里是关键,根据类型的大小确定堆大小 59MemoryPool* head = (MemoryPool*)new char[s]; //将char*强制转换为MemoryPool* 可读性很差,但却高效的利用了内存空间 60ma++; 61head->next = next; 62freeNode = head; 63for (size_t i = 0; i < EXPANSION; i++){ 64head = (MemoryPool*)new char[s]; 65ma++; 66head->next = next; 67next = head; 68} 69 } 70 class Rational_tem{ 71 private: 72static MemoryPool * memPool; 73int n; 74int d; 75 public: 76Rational_tem(int a = 0, int b = 1) :n(a), d(b){} 77void* operator new (size_t s) 78{ 79return memPool->alloca(s); 80} 81void operator delete(void* doomed, size_t s) 82{ 83return memPool->free(doomed); 84} 85static void newMemPool() 86{ 87memPool = new MemoryPool < Rational_tem > ; 88} 89static void deleteMemPool() 90{ 91delete memPool; 92} 93 };

【分配固定大小对象的内存池】有个地方需要注意:内存池不保证分配出去的内存都能够回收,所有new的对象,必须delete后,才能够正确的回收。所以,内存池销毁时,是通过从链表头开始向下释放资源。
该内存池应用在Rational_tem这样的类大量new、delete,在短时间重复数量越多,提升的速度越快。
转载于:https://www.cnblogs.com/wangpei0522/p/4225029.html

    推荐阅读