#include <iostream>
using namespace std;
template<class type, int blockSize>
class idBlockAlloc {
public:
idBlockAlloc( void );
~idBlockAlloc( void );
void Shutdown( void );
type * Alloc( void );
void Free( type *element );
int GetTotalCount( void ) const { return total; }
int GetAllocCount( void ) const { return active; }
int GetFreeCount( void ) const { return total - active; }
private:
typedef struct element_s {
struct element_s * next;
type t;
} element_t;
typedef struct block_s {
element_t elements[blockSize];
struct block_s * next;
} block_t;
block_t * blocks;
element_t * free;
int total;
int active;
};
template<class type, int blockSize>
idBlockAlloc<type,blockSize>::idBlockAlloc( void ) {
blocks = NULL;
free = NULL;
total = active = 0;
}
template<class type, int blockSize>
idBlockAlloc<type,blockSize>::~idBlockAlloc( void ) {
Shutdown();
}
template<class type, int blockSize>
type *idBlockAlloc<type,blockSize>::Alloc( void ) {
if ( !free ) {
block_t *block = new block_t;
block->next = blocks;
blocks = block;
for ( int i = 0; i < blockSize; i++ ) {
block->elements[i].next = free;
free = &block->elements[i];
}
total += blockSize;
}
active++;
element_t *element = free;
free = free->next;
element->next = NULL;
return &element->t;
}
template<class type, int blockSize>
void idBlockAlloc<type,blockSize>::Free( type *t ) {
element_t *element = (element_t *)( ( (unsigned char *) t ) - ( (int) &((element_t *)0)->t ) );
element->next = free;
free = element;
active--;
}
template<class type, int blockSize>
void idBlockAlloc<type,blockSize>::Shutdown( void ) {
while( blocks ) {
block_t *block = blocks;
blocks = blocks->next;
delete block;
}
blocks = NULL;
free = NULL;
total = active = 0;
}
struct SomeClass{
SomeClass(){
cout << "SomeClass()" << endl;
}
};
int main() {
idBlockAlloc<SomeClass,32> eventAllocator;
SomeClass* event = eventAllocator.Alloc();
eventAllocator.Free( event );
}