This is the short version template class, with the important methods:
template<class T>
class Matrix
{
protected:
int width;
int height;
T ** values;
public:
Matrix(int width, int height);
~Matrix();
T get(int i, int j);
void set(int i, int j, T value);
};
template<class T>
Matrix<T>::Matrix(int width, int height) {
this->width = width;
this->height = height;
this->values = new T*[width];
for(int i=0; i<width; i++)
this->values[i] = new T[height];
}
template<class T>
Matrix<T>::~Matrix() {
cout << "~ 1" << endl;
for(int i=0; i<this->width; i++) {
cout << "~ 2" << endl;
for(int j=0; j<this->height; j++) {
cout << "~ 3" << endl;
delete [] &this->values[i][j];
}
cout << "~ 4" << endl;
delete [] &this->values[i];
cout << "~ 5" << endl;
}
}
template<class T>
T Matrix<T>::get(int i, int j) {
return this->values[i][j];
}
template<class T>
void Matrix<T>::set(int i, int j, T value) {
this->values[i][j] = value;
}
In my main project, every time the executable needs delete an object from this class, the program exits with a segmentation fault error.
Below a small program where the error also occurs:
int main() {
cout << "1" << endl;
Matrix<int> * matrix = new Matrix<int>(300, 300);
cout << "2" << endl;
for(int i=0; i<300; i++)
for(int j=0; j<300; j++)
matrix->set(i, j, i+j);
cout << "3" << endl;
delete matrix;
cout << "4" << endl;
return 1;
}
Anyone can tell me what's wrong with this destructor?