我在我的C++应用程序中遇到了一个错误,我在调试时遇到了麻烦。我在网上看过,而且我似乎是以正确的方式完成我的所有分配/释放。这里是我的代码:用模板取消分配动态二维数组
template <typename T>
class Matrix
{
private:
int _rows;
int _cols;
T** _matrix;
public:
Matrix(int r, int c);
~Matrix();
T GetValue(int r, int c);
};
template <typename T>
Matrix<T>::Matrix(int r, int c)
{
_rows = r;
_cols = c;
_matrix = new T*[_rows];
for(int i = 0; i < _rows; i++)
_matrix[i] = new T[_cols];
for(int i = 0; i < _rows; i++)
for(int j = 0; j < _cols; j++)
_matrix[i][j] = NULL;
}
template <typename T>
Matrix<T>::~Matrix()
{
for(int i = 0; i < _rows; i++)
delete [] _matrix[i];
delete [] _matrix;
}
template <typename T>
T Matrix<T>::GetValue(int r, int c)
{
if(r < 0 || r >= _rows || c < 0 || c > _cols)
{
throw -1;
return NULL;
}
return _matrix[r][c];
}
我的客户端代码......
int main()
{
Matrix<int> myMatrix(3, 3);
myMatrix.GetValue(1, 1);
// myMatrix.~Matrix(); // Don't do this anymore
}
只要变量“myMatrix的”超出范围,我得到这个错误:
未处理的异常在0x103159da(msvcr1000d.dll)...访问冲突读取位置0xfeeefee2。
而我被带到文件“dbgdel.cpp” _ASSERTE(_BLOCK_TYPE_IS_VALID(pHead-> nBlockUse));
请帮忙!
编辑:
好了,我忘了给一些信息。请看下面:
我有一个叫做“T Dot(矩阵)”的附加方法我也有两个叫做“Columns()”和“Rows()”的方法,它们只是_cols和_rows的getters。还有一个名为“SetValue(int r,int c,T value)”的方法,它设置_matrix[r][c] = value
。我不认为这些实施是必要的。
template <typename T>
T Matrix<T>::Dot(Matrix<T> m)
{
if(_cols > 1 || m.Columns() > 1 || _rows != m.Rows())
{
throw -1;
return NULL;
}
T value = 0;
for(int i = 0; i < _rows; i++)
{
value += _matrix[i][0] * m.GetValue(i, 0);
}
return value; // Whoops, this was here, just forgot to type it
}
而且客户端...
int main()
{
Matrix<int> intM1(3, 1);
Matrix<int> intM2(3, 1);
intM1.SetValue(0, 0, 1);
intM1.SetValue(1, 0, 1);
intM1.SetValue(2, 0, 1);
intM2.SetValue(0, 0, 1);
intM2.SetValue(1, 0, 1);
intM2.SetValue(2, 0, 1);
std::cout << intM1.Dot(intM2) << endl;
}
这会产生同样的错误如上,但只有当 “点()” 函数被调用。
你有没有尝试从你的主函数中删除myMatrix。〜Matrix()?一旦对象超出范围,析构函数会自动调用,您不应该明确地调用它。 – Connman
@Connman。谢谢,我知道析构函数被自动调用,但我把它作为一个测试。我可以发誓,即使我没有在那里发现错误,但当然,现在他们已经消失了,我已经问过这个问题。我将尝试重现我几小时前的事情。 – Eric
@Eric,如果您不使用它,请不要在您的问题中输入这样的误导性代码。见编辑的答案。 – iammilind