Game Development Reference
In-Depth Information
This function starts by allocating a new array of pointers. This array will hold all of
the blocks of memory chunks that are allocated. It starts with only one element and
adds more if the memory pool needs to grow. After that, it copies any existing blocks
to the new array. Now that the array is in order, a new block of memory is allocated
by calling AllocateNewMemoryBlock() and assigned to the end of the array.
Inside AllocateNewMemoryBlock() , a new block of memory is allocated. Notice
that the true size of each chunk is the size requested, plus the CHUNK_HEADER_SIZE ,
which is defined as follows:
const static size_t CHUNK_HEADER_SIZE = (sizeof(unsigned char*));
This is the header data that will point to the next element. After the block has been
allocated, the function walks through each chunk in the block and points the header
to the next block. This sets up the singly linked list. After that, you
'
re ready to go,
and the new block is returned to GrowMemoryArray() .
Now that the GrowMemoryArray() function has the newly constructed block, it
checks to see if m_pHead is valid. This is the pointer to the front of the list. If it
s
valid, it must walk through the list of chunks to find the end and append it there. If
not, the new block can be attached right there. Currently, GrowMemoryArray() is
only called when you
'
ve run out of
chunks. In both of these cases, m_pHead will be NULL . The extra clause is there in
case you want the ability to grow the memory at any time.
That ' s pretty much it. Once GrowMemoryArray() returns, you ' ll have a brand new
block of memory ready to be dished out. Now that all the heavy lifting is done, the
Alloc() and Free() functions become very simple:
'
re initializing the memory pool or when you
'
void* MemoryPool::Alloc(void)
{
// If we
re out of memory chunks, grow the pool. This is very expensive.
if (!m_pHead)
{
'
// if we don
t allow resizes, return NULL
if (!m_toAllowResize)
return NULL;
'
// attempt to grow the pool
if (!GrowMemoryArray())
return NULL; // couldn
'
t allocate anymore memory
}
// grab the first chunk from the list and move to the next chunks
unsigned char* pRet = m_pHead;
Search WWH ::




Custom Search