Game Development Reference
In-Depth Information
Listing 22-5 begins by showing you a structure that will be used as a header for our memory
allocations.
Listing 22-5. The
MemoryAllocationHeader struct
struct MemoryAllocationHeader
{
void* pStart{ nullptr };
void* pNextFree{ nullptr };
size_t size{ 0 };
};
This
struct
stores a pointer to the memory returned to the user in the
pStart void*
variable,
a pointer to the next free block of memory in the
pNextFree
pointer, and the size of the allocated
memory in the
size
variable.
Our memory manager isn't going to use dynamic memory to allocate memory to the user's program.
Instead it is going to return an address from inside a static array. This array is created in an unnamed
namespace shown in Listing 22-6.
Listing 22-6. The Unnamed
namespace
from
Chapter22-MemoryAllocator.cpp
namespace
{
const unsigned int ONE_MEGABYTE = 1024 * 1024 * 1024;
char pMemoryHeap[ONE_MEGABYTE];
const size_t SIZE_OF_MEMORY_HEADER = sizeof(MemoryAllocationHeader);
}
Here you can see that we allocate a static array of 1 MB in size. We know that this is 1 MB as the
char
type is one byte in size on most platforms and we are allocating an array that is 1,024 bytes
times 1,024 KB in size for a total of 1,048,576 bytes. The unnamed namespace also has a constant
storing the size of our
MemoryAllocationHeader
object, calculated using the
sizeof
function. This
size is 12 bytes: 4 bytes for the
pStart
pointer, 4 bytes for the
pNextFree
pointer, and 4 bytes for the
size
variable.
The next important piece for code overloads the new operator. The
new
and
delete
functions that
you have seen so far are just functions that can be hidden in the same way you can hide any other
function with your own implementation. Listing 22-7 shows our new function.
Listing 22-7. The Overloaded
new
Function
void* operator new(size_t size)
{
MemoryAllocationHeader* pHeader =
reinterpret_cast<MemoryAllocationHeader*>(pMemoryHeap);
while (pHeader != nullptr && pHeader->pNextFree != nullptr)
{
pHeader = reinterpret_cast<MemoryAllocationHeader*>(pHeader->pNextFree);
}