I'm trying to implement Vector in C++ and I faced a memory problem delete the array. This is my code:
template<class T>
class Vector {
T* _vector;
size_t _size;
size_t _capacity;
public:
Vector() : _vector(nullptr), _size(0), _capacity(0) {};
Vector(const int &capacity) : _capacity(capacity) {
_vector = (T*)malloc(capacity * sizeof(T));
}
Vector<T>& pushBack(const T &t) {
_size++;
if (_capacity >= _size)
_vector[_size - 1] = t;
else {
_capacity <<= 1;
_vector = (T*)realloc(_vector, _size * sizeof(T));
_vector[_size - 1] = t;
}
return *this;
}
virtual ~Vector() { delete[] _vector; }
};
I tried to do a fluent programming in order to be able making this in main:
int main() {
Vector<int> v();
v.pushBack(42).pushBack(100);
}
after debugging this I noticed that the fluent programming cause the destructor HEAP CORRUPTION ERROR, anyone knows why?
Also, is there a better "C++" way to realloc the T array?
Thanks!
EDIT: I changed all malloc/realloc functions in the class to new T[size] and now it's o.k.