記憶體池實現有許多種,各有不同的優缺點。
這裡不是主要說記憶體池,只是覺得這個記憶體池中的指標用得很飄逸!
template <class T,int AllocSize = 50><br />class MemPool<br />{<br />public:<br />static void* operator new(size_t allocLength)<br />{<br />if(!mStartPotinter)<br />{<br />MyAlloc();<br />}<br />//將當前指向空閑記憶體起始地址作為反回地址<br />unsigned char* p = mStartPotinter;<br />//取出空閑地區前4位元組的值,賦值給空閑地址<br />//因為前四位元組中存放了下一個BLOCK的地址<br />mStartPotinter = *(unsigned char**)mStartPotinter;<br />return p;<br />}</p><p>static void operator delete(void* deleteP)<br />{<br />//assert(deletePointer);<br />*(unsigned char**)deleteP = mStartPotinter;<br />mStartPotinter = (unsigned char*)deleteP;<br />}</p><p>static void MyAlloc()<br />{<br />//預分配記憶體<br />mStartPotinter = new unsigned char[sizeof(T)*AllocSize];<br />//構造BLOCK之間的關係<br />//每個BLOCK的前4BYTE存放了下一個BLOCK的地址<br />unsigned char** next = (unsigned char**)mStartPotinter;<br />unsigned char* p = mStartPotinter;</p><p>for(int i = 0; i< AllocSize;++i)<br />{<br />p +=sizeof(T);//步進<br />*next = p;//賦值<br />next = (unsigned char**)p;//步進<br />}<br />*next = NULL;<br />}</p><p>static unsigned char* mStartPotinter;<br />};</p><p>template <class T,int AllocSize><br />unsigned char* MemPool<T,AllocSize>::mStartPotinter = NULL;
簡單提示一下: 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)<br /> {<br /> p +=sizeof(T);//步進<br /> unsigned char* pp = (unsigned char*)(p[sizeof(T)*i]);<br /> pp = p;//賦值<br /> }
不想多解釋了,累。估計多看幾分種啥都明白了!