PiotrK
PiotrK

Reputation: 4453

Custom implementation of STL std::vector

I am writing for platform that does not have build in STL but do have templates support

I am working on my own std::vector implementation.

template<typename T> class Array
{
private:
    T * buffer;
    int count;
    int capacity;
public:
    Array() : buffer(0), count(0), capacit(0) { }
    ~Array() { if(buffer) delete[] buffer; }
    void IN_ANY Reserve(const int capacity)
    {
        if(capacity >= count)
        {
            T * newBuff = new T[capacity];
            if(capacity > count)
                memset(newBuff+count, 0, (capacity-count) * sizeof(T));
            memcpy(newBuff, buffer, count * sizeof(T));

            if(buffer)
                delete [] buffer;

            buffer = newBuff;
            this->capacity = capacity;
        }
    }
    // Other methods...
}

The problem comes when T has non-trival constructor, non-trival destruction and overloaded operator=. Then, when Reserving additional memory for array, destructors for T will be called, and than constructors. But not copy constructor (since I used memcpy). How could I improve Reserve method?

Upvotes: 0

Views: 325

Answers (3)

Stripes
Stripes

Reputation: 4229

If you really want to know how to implement big parts of the STL, go get the "The C++ Standard Template Library" book by P.J. Plauger, Alexander Stepanov, Meng Lee, and David R. Musser.

Along with use and some standards interpretation is also goes over how to implement large parts of the STL. It is a fairly old book, but very interesting for seeing what goes on under the covers.

If you don't so much want to know how to do it, but more just want it done, go with one of the other answers about looking at source forge projects.

Upvotes: 1

PiotrK
PiotrK

Reputation: 4453

The answer I was looking for was placement new

Upvotes: -1

StilesCrisis
StilesCrisis

Reputation: 16290

Don't roll your own--use STLPort. http://sourceforge.net/projects/stlport/

It's a free and highly portable STL implementation.

Upvotes: 2

Related Questions