I am attempting to learn how to assign memory in C++. I followed this answer to allocating 2-D arrays: Copy 2D array using memcpy?
However, when I attempt to combine this and copying memory using std::copy I get a corruption.
#include <iostream>
class Matrix
{
private:
int nrows;
int mcols;
double **entry;
public:
Matrix(int n, int m);
~Matrix();
Matrix& operator=(const Matrix& mat_in);
};
Matrix::Matrix(int n, int m)
{
nrows = n;
mcols = m;
std::cout << "Using regular constructor" << std::endl;
entry = new double*[nrows];
entry[0] = new double[nrows * mcols];
for(int i=1;i<nrows;i++)
entry[i] = entry[i-1] + mcols;
for(int i=0;i<nrows;i++)
for(int j=0;j<mcols;j++)
entry[i][j] = 0.0;
}
Matrix::~Matrix()
{
delete[] entry[0];
delete[] entry;
}
Matrix& Matrix::operator=(const Matrix& mat_in)
{
std::cout << "using deep copy constructor" << std::endl;
if(this == &mat_in)
return *this;
double **p = new double*[mat_in.nrows];
p[0] = new double[mat_in.nrows * mat_in.mcols];
std::copy(mat_in.entry, mat_in.entry + (mat_in.nrows * mat_in.mcols), p);
delete[] this -> entry;
entry = p;
nrows = mat_in.nrows;
mcols = mat_in.mcols;
return *this;
}
int main()
{
Matrix A(3,3);
Matrix B(3,3);
B = A;
return 0;
}
I think the problem is that I don't fully understand what is happening when I free the memory and I am freeing it twice.