[ create a new paste ] login | about

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

joel_f - C++, pasted on Oct 26:
#include <cstddef>

template< class Type
        , std::size_t Size = 1024*1024*sizeof(Type)
        , std::size_t ID = sizeof(Type)
        >
struct heapless_allocator
{
  static Type* allocate()
  {
    Type* mem = new(next) Type;
    next += sizeof(Type); // miss alginement stuff and error checkign
    return mem;
  }

  static Type* allocate( std::size_t nb )
  {
    Type* mem = new(next) Type[nb];
    next += nb*sizeof(Type); // miss alginement stuff and error checkign
    return mem;
  }

  static void release( Type* ptr )
  {
    ptr->~Type(); // is it enough ?
  }

  static void release( Type* ptr, std::size_t nb )
  {
  }

  static unsigned char   buffer[Size];
  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];

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>::allocate();
  cout << mem << endl;
  heapless_allocator<foo>::release(mem);
}


Output:
1
2
3
allocating foo @0x8050840
0x8050840
deallocating foo @0x8050840


Create a new paste based on this one


Comments: