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?
The answer I was looking for was placement new