Original Post
I'm writing a memory allocation class to be used for several "temporary" objects in my game. These objects only need to exist for a single frame, and don't do anything meaningful in their destructors. My class is designed to have a fixed size heap and an index of the first unused byte in the heap. Allocations increment the index, and at the end of the frame I clear the heap by resetting the index to 0 (the objects are "leaked", but the memory is reused). What I'm not quite sure about, is how exactly I should be aligning these allocations. I've been warned that you should only use placement new if you know how to handle alignment, so I'm kind of uneasy. At the moment, I'm aligning the allocations to 4-byte boundaries like so:Usage: [Edit:] I just realised that my code is aligning the offset from the beginning of my buffer, not the actual memory address! I'll have to fix this. [Edited by - Hodgman on May 6, 2009 12:58:42 AM]
namespace {
const static uint gs_Alignment = sizeof(int);
}The allocation code://m_Heap is a std::vector<char>, m_Usage is an unsigned int.
CTempHeap::CTempHeap( size_t heap )
{
m_Heap.resize( heap );
m_Usage = 0;
}
void* CTempHeap::Alloc( size_t size )
{
uint startByte = m_Usage;
startByte = ((startByte+(gs_Alignment-1))/gs_Alignment)*gs_Alignment;
uint newUsage = startByte + size;
if( newUsage >= m_Heap.size() )
return NULL;
m_Usage = newUsage;
return &m_Heap[startByte];
}
void CTempHeap::Clear()
{
m_Usage = 0;
}
void* CTempObj::operator new( size_t size, CTempHeap& w )
{
void* p = w.Alloc( size );
if( !p )//TODO - use the new handler
throw std::bad_alloc();
return p;
}
CTempHeap heap( 1024 );//1kb heap
CTempObj* pTest = new(heap) CTempObj;
pTest = 0;
heap.Clear();