samedi 24 mars 2018

Implementing a simple allocator class using malloc() and free()

Is this simple implementation of an allocator acceptable

template<typename 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<typename T>
T* Allocator<T>::allocate(int n)
{
    T* new_mem = (T*)malloc(n * sizeof(T));
    return new_mem;
}

template<typename T>
void Allocator<T>::construct(T* p, const T& v)
{
    T* constructed_object = new(p) T{ v };
}

template<typename T>
void Allocator<T>::deallocate(T* p, int n)
{
    for (int i = 0; i < n; ++i)
    {
        free(&p[i]);
    }
}

template<typename T>
void Allocator<T>::destroy(T* p)
{
    p->~T();
}

I'm to use it in a vector to implement function that reserves exra space as follows:

template<typename T, typename A>
void vector<T, A>::reserve(int newalloc)
{
    if (newalloc <= space)return;
    T* p = alloc.allocate(newalloc);
    for (int i = 0; i < sz; ++i)alloc.construct(&p[i], elem[i]);
    for (int i = 0; i < sz; ++i)alloc.destroy(&elem[i]);
    elem = p;
    space = newalloc;
}

where typename A = Allocator<T> and alloc is of type A. Will the allocator class I implemented be functional enough to work? (I feel the deallocate function is suspect)

Aucun commentaire:

Enregistrer un commentaire