Lecture Notes for Advanced Programming II

16 December 2003 - Allocators


A Simple Vector Class

template < typename T >
class vtr

  public:

    vtr() : elements(0), size(0), max(0) { }

    void push_back(const T & v)
      if size >= max, grow()
      assert(size <= max)
      elements[size++] = v

  private:

    T * elements
    size_t size, max

    void grow()
      max = (max == 0 ? 1 : max*2)
      T * const ne = new T [max]
      for size_t i = 0; i < size; i++
	ne[i] = elements[i]
      delete [] elements
      elements = ne


An Expensive Vector Class


The memcpy() Optimization


C vs. C++ Storage Management


Allocators


Storage Management


Storage Allocation and Deallocation


Storage Initialization and Clean-Up


new and delete


The Allocator Storage-Management Abstraction


The Allocator Class


An Improved Vector Class

template <typename T> class avtr

  public:

   ~avtr() { uncreate() }

  private:

    std::allocator<T> alloc

    void grow()
      max_size = max(max_size*2, ptrdiff_t(1))
      T * ne = alloc.allocator(max_size)
      uninitialized_copy(data, data + size, ne)
      uncreate()
      data = ne

    void uncreate()
      for i = data + size - 1; i != data; i--
	alloc.destroy(i)
      alloc.deallocate(data, size)


Does It Work?


This page last modified on 19 December 2003.