某內存池中的指針用法
內存池實現有許多種,各有不同的優缺點。
這里不是主要說內存池,只是覺得這個內存池中的指針用得很飄逸!
template <class T,int AllocSize = 50> 2
class MemPool 3


{ 4
public: 5
static void* operator new(size_t allocLength) 6

{ 7
if(!mStartPotinter) 8

{ 9
MyAlloc(); 10
} 11
//將當前指向空閑內存起始地址作為反回地址 12
unsigned char* p = mStartPotinter; 13
//取出空閑區域前4字節的值,賦值給空閑地址 14
//因為前四字節中存放了下一個BLOCK的地址 15
mStartPotinter = *(unsigned char**)mStartPotinter; 16
return p; 17
} 18
19
static void operator delete(void* deleteP) 20

{ 21
// assert(deletePointer); 22
*(unsigned char**)deleteP = mStartPotinter; 23
mStartPotinter = (unsigned char*)deleteP; 24
} 25
26
static void MyAlloc() 27

{ 28
//預分配內存 29
mStartPotinter = new unsigned char[sizeof(T)*AllocSize]; 30
//構造BLOCK之間的關系 31
//每個BLOCK的前4BYTE存放了下一個BLOCK的地址 32
unsigned char** next = (unsigned char**)mStartPotinter; 33
unsigned char* p = mStartPotinter; 34
35
for(int i = 0; i< AllocSize;++i) 36

{ 37
p +=sizeof(T);//步進 38
*next = p;//賦值 39
next = (unsigned char**)p;//步進 40
} 41
*next = NULL; 42
} 43
44
static unsigned char* mStartPotinter; 45
}; 46
47
template <class T,int AllocSize> 48
unsigned char* MemPool<T,AllocSize>::mStartPotinter = NULL; 49

50

51
本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/wqjqepr/archive/2010/05/03/5552322.aspx
簡單提示一下: unsigned char** next = (unsigned char**)mStartPotinter;
mStartPotinter作為二維指針的時候,相當于是一系列的unsigned char* [].
對于第一個 *next 相當于(unsigned char*)mStartPointer[0].
第二個相當于(unsigned char*)mStartPointer[sizeof(T)*1];
第三個相當于(unsigned char*)mStartPointer[sizeof(T)*2];
所以,構造BLOCK之間關系的時候,也可以寫成
for(int i = 0; i< AllocSize;++i) 2


{ 3
p +=sizeof(T);//步進 4
unsigned char* pp = (unsigned char*)(p[sizeof(T)*i]); 5
pp = p;//賦值 6
}
不想多解釋了,累。估計多看幾分種啥都明白了!
posted on 2010-05-03 18:33 麒麟子 閱讀(1978) 評論(11) 編輯 收藏 引用 所屬分類: Programming
