Game Development Reference
In-Depth Information
To use this class, instantiate it and call the Init() function. The chunkSize is the
size of each atomic memory chunk, and numChunks is the number of chunks that are
created for each set of chunks. Collectively, this set of chunks is called a block.Ifyou
go over your limit of memory chunks, the memory pool will allocate another block for
you. This isn
'
t catastrophic, but you don
'
t want to make a habit of going over your
limit because it
s very time consuming to set up a new memory block. If Init()
returns true , your memory pool is ready to go! You can call Alloc() and Free()
to allocate and free a chunk, respectively.
The Init() function just sets some member variables and calls the GrowMemor-
yArray() function to allocate the new block of memory. Let
'
'
s take a look inside
GrowMemoryArray() to see how the magic happens:
bool MemoryPool::GrowMemoryArray(void)
{
// allocate a new array
size_t allocationSize = sizeof(unsigned char*) * (m_memArraySize + 1);
unsigned char** ppNewMemArray = (unsigned char**)malloc(allocationSize);
// make sure the allocation succeeded
if (!ppNewMemArray)
return false;
// copy any existing memory pointers over
for (unsigned int i = 0; i < m_memArraySize; ++i)
{
ppNewMemArray[i] = m_ppRawMemoryArray[i];
}
// Allocate a new block of memory. Indexing m_memArraySize here is
// safe because we haven
t incremented it yet to reflect the new size
ppNewMemArray[m_memArraySize] = AllocateNewMemoryBlock();
'
// attach the block to the end of the current memory list
if (m_pHead)
{
unsigned char* pCurr = m_pHead;
unsigned char* pNext = GetNext(m_pHead);
while (pNext)
{
pCurr = pNext;
pNext = GetNext(pNext);
}
SetNext(pCurr, ppNewMemArray[m_memArraySize]);
}
Search WWH ::




Custom Search