1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
#include <memory>
//------------------------------------------------------------------------------
template<class T> class allocator {
public:
// ...
T* allocate(int n); // allocate space for n objects of type T
void deallocate(T* p, int n); // deallocate n objects of type T starting at p
void construct(T* p, const T& v); // construct a T with the value v in p
void destroy(T* p); // destroy the T in p
};
//------------------------------------------------------------------------------
template<class T, class A>
struct vector_base {
A alloc; // allocator
T* elem; // start of allocation
int sz; // number of elements
int space; // amount of allocated space
vector_base(): elem(0), sz(0), space(0) {}
vector_base(const A& a, int n)
: alloc(a), elem(a.allocate(n)), sz(n), space(n) { }
~vector_base() { alloc.deallocate(elem,space); }
};
//------------------------------------------------------------------------------
template<class T, class A>
void swap(vector_base<T,A>& a, vector_base<T,A>& b);
//------------------------------------------------------------------------------
template<class T, class A = allocator<T> >
class vector : private vector_base<T,A> {
public:
explicit vector(int n, const T& val = T(), const A& a = A());
void reserve(int newalloc);
};
//------------------------------------------------------------------------------
template<class T, class A>
vector<T,A>::vector(int n, const T& val, const A& a)
:vector_base<T,A>(a,n)
{
std::uninitialized_fill(this->elem,(this->elem)+n,val);
}
//------------------------------------------------------------------------------
template<class T, class A>
void vector<T,A>::reserve(int newalloc)
{
if (newalloc<=this->space) return; // never decrease allocation
vector_base<T,A> b(this->alloc,newalloc); // allocate new space
for (int i=0; i<this->sz; ++i) this->alloc.construct(&b.elem[i],this->elem[i]); // copy
for (int i=0; i<this->sz; ++i) this->alloc.destroy(&this->elem[i]); // destroy old
swap< vector_base<T,A> >(*this,b); // swap representations
}
//------------------------------------------------------------------------------
int main()
{
vector<int,allocator<int> > v(10);
}
//------------------------------------------------------------------------------ |