[ create a new paste ] login | about

Link: http://codepad.org/zCJpArvT    [ raw code | output | fork ]

joel_f - C++, pasted on Oct 26:
#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;
}


Output:
allocating foo @0x8050a1c
0x8050a1c
deallocating foo @0x8050a1c

allocating foo @0x8050a1d
allocating foo @0x8050a1e
allocating foo @0x8050a1f
allocating foo @0x8050a20
allocating foo @0x8050a21
allocating foo @0x8050a22
allocating foo @0x8050a23
0x8050a1d
deallocating foo @0x8050a1d
deallocating foo @0x8050a1e
deallocating foo @0x8050a1f
deallocating foo @0x8050a20
deallocating foo @0x8050a21
deallocating foo @0x8050a22
deallocating foo @0x8050a23

0



Create a new paste based on this one


Comments: