我在我的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