I have a matrix class and, with the following constructor:
template<class T>
Matrix<T>::Matrix(unsigned rows, unsigned cols) :
rows(rows), cols(cols) {
index = 0;
data_ = new T[rows * cols];
}
template<class T>
Matrix<T>::~Matrix() {
delete[] data_;
}
When I’m calculating the inverse of the matrix, I would like to free the memory of the
temporary variable called a:
template<class T>
Matrix<T> Matrix<T>::inverse() {
unsigned i, j, k;
Matrix<T> a(2 * rows, 2 * rows);
....
return tmp;
}
I thought that this variable would be destroyed in the end of the function, but when I test:
for (int i = 0; i < 3; i++) {
Matrix<double> m(5, 5);
m << 5, 2, 4, 5, 6, 1, 3, 1, 2, 5, 2, 5, 2, 7, 2, 9, 2, 1, 0.1, 0.43, 1, 0, 0, 0, 1;
m.inverse();
std::cout << m << std::endl;
}
In the first loop the a is initialized with zeros, but the next step the initial values of the a is the previous values, so a(k+1)=a_endvalues(k). Why is it like this?
The problem is that you are not initializing the elements of your dynamically allocated array in the constructor. To ensure that the array has default constructed or zero-initialized elements, you need to do this in your constructor:
But as has been pointed out in comments, you could make your life easier by using an
std::vector<T>: