#include <cstddef>
template< class Type
, std::size_t Size = 1024*1024
, std::size_t ID = sizeof(Type)
>
struct heapless_allocator
{
static Type* allocate()
{
if( next+sizeof(Type) <= end )
{
Type* mem = new(next) Type;
next += sizeof(Type); // miss alginement stuff and error checkign
return mem;
}
else
return 0;
}
static Type* allocate( std::size_t nb )
{
if( next+nb*sizeof(Type) <= end )
{
Type* mem = new(next) Type[nb];
next += nb*sizeof(Type); // miss alginement stuff and error checkign
return mem;
}
else
return 0;
}
static void release( Type* ptr )
{
ptr->~Type(); // is it enough ?
}
static void release( Type* ptr, std::size_t nb )
{
// there is nb objects from there
for(std::size_t i=0;i<nb;++i)
(ptr++)->~Type();
}
static unsigned char buffer[Size*sizeof(Type)];
static Type* next;
static Type* end;
};
template<class Type, std::size_t Size, std::size_t ID>
unsigned char heapless_allocator<Type,Size,ID>::buffer[Size*sizeof(Type)];
template<class Type, std::size_t Size, std::size_t ID>
Type* heapless_allocator<Type,Size,ID>::next
= (Type*)(&heapless_allocator<Type,Size,ID>::buffer[0]);
template<class Type, std::size_t Size, std::size_t ID>
Type* heapless_allocator<Type,Size,ID>::end
= (Type*)(&heapless_allocator<Type,Size,ID>::buffer[Size]);
struct foo
{
foo() { cout << "allocating foo @" << this << endl; }
~foo() { cout << "deallocating foo @" << this << endl; }
};
int main()
{
foo* mem = heapless_allocator<foo,8>::allocate();
cout << mem << endl;
heapless_allocator<foo>::release(mem);
cout << endl;
mem = heapless_allocator<foo,8>::allocate(7);
cout << mem << endl;
heapless_allocator<foo>::release(mem,7);
cout << endl;
mem = heapless_allocator<foo,8>::allocate();
cout << mem << endl;
cout << endl;
}