I have a class named Matrix. There is a 2D array in the class to save the data.
template <class Type>
class Matrix{
public:
Matrix(int row, int col){
rows = row; cols = col;
data = new Type*[rows];
for(int i = 0; i < rows; i++){
data[i] = new Type[cols];
}
}
public:
int rows;
int cols;
Type **data;
};
And I have a vector to save the Matrix. Every time I have a Matrix, I will push back the matrix in this vector for future calculation. In order to avoid memory leak, I want to delete the Matrix after pushing it back to the vector. But if I don't delete it, the program works; if I delete it (as shown in the code below), the program will show the segmentation fault when I want to do some calculation for this vector. The code I used is shown below
vector<Matrix<int>> v;
for(int i = 0; i < 10; ++i){
Matrix<int> a(3,3);
...... // I fill the elements of a.data
v.push_back(a);
for(int j = 0; j < a.rows; ++j)
delete[] a.data[j];
delete[] a.data;
}
Hope I have explained my problem clearly. If anything makes you confuse, please comment me.
Thanks for help!!!