I have an Array template class which looks like this
template <typename T>
class Array {
private:
T *_array;
int _arrSize;
public:
Array<T>() : _arrSize(0) {
T *a = new T[0];
this->_array = a;
};
Array<T>(unsigned int n) : _arrSize(n) {
T *a = new T[n];
this->_array = a;
};
Array<T>(Array<T> const ©) : _array(copy._array), _arrSize(copy._arrSize) {
*this = copy;
return;
};
template <typename G>
Array<T> &operator=(Array<G> const &rhs) {
if (&rhs != this) {
Array<T> tmp(rhs);
std::swap(*this, tmp);
}
return *this;
};
~Array<T>() {
delete[] this->_array;
this->_array = NULL;
};
T &getArray() const {
return this->_array;
}
Which works fine until I try to do the assignment
Array<int> g;
Array<int> i(3);
i[1] = 99;
g = i;
then I get an error
array(99457,0x10f5f25c0) malloc: *** error for object 0x7fc390c02aa0: pointer being freed was not allocated array(99457,0x10f5f25c0) malloc: *** set a breakpoint in malloc_error_break to debug zsh: abort ./array
which obviously comes from the destructor here
delete[] this->_array;
I'm not sure how to write the assignment operator correctly to avoid this error.