用模版实现简单的内存池
生活随笔
收集整理的這篇文章主要介紹了
用模版实现简单的内存池
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
程序中有時候會遇到這種情況,就是需要不停的去分配以及釋放內存。帶來的是不停的調用new以及delete帶來的開銷。
而且由于全局的new以及delete往往對多線程做出了并發保護,所以在單線程情況下這更帶來一種浪費,一般的情況下是去實現一個
單線程的內存池來進行性能優化,配合所需的類往往帶來很好的性能提升。
首先是作為內存池的模板類:
1 template<class T> 2 class MemoryPool{ 3 public: 4 MemoryPool(size_t size = EXPANSION_SIZE); 5 ~MemoryPool(); 6 7 //從空閑列表中分配T大小的空間 8 inline void * alloc(size_t size); 9 10 //釋放內存到空閑列表中 11 inline void free(void * elements); 12 private: 13 MemoryPool<T> * next; //空閑列表的下一個元素 14 enum { EXPANSION_SIZE = 32 }; 15 void expandTheFreeList(int howMany = EXPANSION_SIZE); 16 }; 17 18 template<class T> 19 MemoryPool<T>::MemoryPool(size_t size) 20 { 21 expandTheFreeList(size); 22 } 23 24 template<class T> 25 MemoryPool<T>::~MemoryPool() 26 { 27 MemoryPool<T> * nextPtr = next; 28 if (next){ 29 for (nextPtr = next; nextPtr != nullptr; nextPtr = next){ 30 next = next->next; 31 delete[] ((char * )nextPtr); //這里的強制類型轉換應該注意,不轉換編譯無法通過的當時分配 32 //內存的時候是按照char類型分配的,那么釋放的時候也應該同樣釋放。 33 } 34 } 35 } 36 37 38 template<class T> 39 inline 40 void * MemoryPool<T>::alloc(size_t) 41 { 42 if (!next) 43 expandTheFreeList(); 44 MemoryPool<T> * head = next; 45 next = head->next;//分配了一塊空間 46 return head; 47 } 48 49 template<class T> 50 inline 51 void MemoryPool<T>::free(void * doomed) 52 { 53 MemoryPool<T> * head = static_cast<MemoryPool<T> *>(doomed); 54 head->next = next; 55 next = head; 56 } 57 58 template<class T> 59 void MemoryPool<T>::expandTheFreeList(int howMany) 60 { 61 //保證分配的內存大小至少應該是大于指針大小或者是元素大小中的 最大者,因為二者之間是共享內存的 62 size_t sizeAlloc = (sizeof(T) > sizeof(MemoryPool<T> *)) ? 63 sizeof(T) : sizeof(MemoryPool<T> *); 64 MemoryPool<T> * runner = (MemoryPool<T>*)(new char[sizeAlloc]); //這里實際上是可以使用static_cast的,但是不知道為什么, 65 next = runner; //gcc下編譯不能通過。可能因為gcc的限制比較嚴格。無奈,只能使用普通的強制類型轉換 66 for (int i = 0; i < howMany; ++i){ 67 runner->next = (MemoryPool<T>*)(new char[sizeAlloc]); 68 runner = runner->next; 69 } 70 runner->next = 0; 71 }?
下面是使用該內存池的一個rational類,代碼如下:
1 class Rational{ 2 public: 3 Rational(int a = 0, int b = 1):n(a), d(b){} 4 void * operator new(size_t size){return memPool->alloc(size); } 5 void operator delete(void * doomed, size_t size){memPool->free(doomed);} 6 static void newMemPool(){memPool = new MemoryPool<Rational>; } 7 static void deleteMemPool() 8 { 9 if(!memPool) 10 return; 11 delete memPool; 12 } 13 private: 14 int n; 15 int d; 16 static MemoryPool <Rational> * memPool; 17 };使用代碼如下:
1 MemoryPool<Rational> * Rational::memPool = 0; 2 3 int main() 4 { 5 Rational * array[10]; 6 Rational::newMemPool(); 7 for(int j = 0; j < 2; ++j){ 8 for(int i = 0; i < 10; i++){ 9 array[i] = new Rational(i); 10 } 11 for(int i = 0; i < 10; i++){ 12 delete array[i]; 13 } 14 } 15 Rational::deleteMemPool(); 16 }?
轉載于:https://www.cnblogs.com/-wang-cheng/p/4950452.html
總結
以上是生活随笔為你收集整理的用模版实现简单的内存池的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: instanceof的用法①
- 下一篇: 做梦梦到洪水是什么征兆