如何在Matrix类中释放内存? [英] How can I free memory in Matrix Class?
问题描述
我有一个矩阵类,并具有以下构造函数:
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_;
}
当我计算矩阵的逆矩阵时,
临时变量的内存
:
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;
}
在第一个循环中, a
用零初始化,但是下一步, a
的初始值是以前的值,因此 a(k + 1)= a_endvalues(k)
。为什么是这样的?
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:
template<class T>
Matrix<T>::Matrix(unsigned rows, unsigned cols) :
rows(rows), cols(cols) {
index = 0;
data_ = new T[rows * cols]();
// ^ HERE!
}
但是正如评论中所指出的,你可以通过使用 std :: vector< T>
:
But as has been pointed out in comments, you could make your life easier by using an std::vector<T>
:
template<class T>
Matrix<T>::Matrix(unsigned rows, unsigned cols) :
rows(rows), cols(cols), data_(rows*cols)
{ }
这篇关于如何在Matrix类中释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!