Annoyance over C++’s requirement to pass a dimension in a 2-d array got me working on a templated Matrix class. I’ve been coding in C# for a bit, so I’m sure I’m a little rusty here.
Issue is, I get a heap exception as soon as I hit the destructor, which is trying to delete the 2-d array.
Any help gratefully accepted!
template <typename T>
class Matrix {
public:
Matrix(int m, int n) : nRows(m), nCols(n) {
pMatrix = new T * [nRows];
for (int i = 0; i < nCols; i++) {
pMatrix[i] = new T[nCols];
}
}
~Matrix() {
if (pMatrix != NULL) {
for (int i = 0; i < nRows; i++) { delete[] pMatrix[i]; }
delete[] pMatrix;
}
}
T ** GetMatrix() const { return pMatrix; }
T * Row(int i) const { return pMatrix[i]; }
inline T Cell(int row, int col) const { return pMatrix[row][col]; }
inline int GetNRows() const { return nRows; }
inline int GetNCols() const { return nCols; }
private:
int nRows, nCols;
T ** pMatrix;
};
Concerning the bug, @CodeChords_man explained it right. I have notes on implementation. I recommend to look through this wonderful FAQ post.
You should not use dynamic memory allocation unless you are 100% sure that
I don’t know of the first, and how the performance is crucial for you. But as for the second, you at least violated the rule of three. You class is very unsafe to use. If you copy it, the memory buffer will then be double-deleted.
You should not afraid to used STL containers, they are fast and optimized. At least the
std::vector, it is as fast as the raw pointer in many scenarios. You can rewrite you class usingstd::vectoras follows:Since this class is not using dynamic memory allocation, it is safe to copy and assign. You also don’t need to explicitly store
nRowsandnColsin this case; you can use_body.size()and_body[0].size()instead.Concerning underlying vector of vectors, it is dereferenced using the same
[i][j]construction. It is easily iterated withbegin()andend(). And if you absolutely need to use the raw pointer in some routine, you can always access it with&row[0].The only possible difficulty is that you cannot easily convert
MatrixBodytoT**. But think it twice, maybe you don’t really need to useT**at all.