Minimum template allocator


A minimum template allocator tested on std::vector and std::sort.

It’s just to show how allocators work.
The code is kept to minimum so that the key points can be easily seen.

#include <vector>
#include <cassert>
#include <algorithm>
using namespace std;

template <class T> class Alloc;
template <> struct Alloc<void>
{ typedef const void* const_pointer;
};
template <class T>
class Alloc
{
public:
 typedef size_t size_type;
 typedef ptrdiff_t difference_type;
 typedef T*pointer;
 typedef const T*const_pointer;
 typedef T& reference;
 typedef const T& const_reference;
 typedef T value_type;
 template <class U>
 struct rebind
 { typedef Alloc<U> other;
 };
 Alloc() {}
 template <class U>
 Alloc(const Alloc<U>&) {}
 pointer allocate(size_type num)
 {
  return pointer(malloc(num * sizeof T));
 }
 void deallocate(pointer p, size_type n)
 {
  free(p);
 }
 size_type max_size() const
 {
  return 4;
 }
 void construct(pointer p, const T& val)
 {
  new((void*)p)T(val);
 }
 void destroy(pointer p)
 {
  p->~T();
 }
};
void TestAlloc()
{
 vector<int, Alloc<int>> v;
 v.push_back(2);
 v.push_back(1);
 sort(v.begin(), v.end());
 assert(v[0] == 1);
 assert(v[1] == 2);
}
Advertisements
Comments are closed.
%d bloggers like this: