I am trying to learn the basics of writing my custom constructors but I cannot figure out what I'm doing wrong. I know that for my purposes it would be enough to let the compiler do its' job, but I'm curious how I could fix my definitions.
#include <iostream>
#include <stdexcept>
class Matrix {
public:
Matrix(int rows, int cols); //my custom constructor
~Matrix(); //my custom destructor
Matrix(const Matrix& m); //my custom copy constructor
Matrix& operator= (const Matrix& m); //my custom assignment operator
private:
int rows_, cols_;
double* data_;
};
Matrix::Matrix(int rows, int cols): rows_ (rows), cols_ (cols){
if (rows == 0 || cols == 0)
throw std::out_of_range("Matrix constructor has 0 size");
data_ = new double[rows * cols];
}
Matrix::~Matrix()
{
delete[] data_;
}
Matrix::Matrix(const Matrix& m) : rows_(m.rows_), cols_(m.cols_)
{
data_ = new double[rows_ * cols_];
data_=m.data_;
}
Matrix& Matrix::operator=(const Matrix& m){
if(this != &m){
double* newdata_=new double[m.cols_*m.rows_];
*newdata_=*data_;
delete[] data_;
data_=newdata_;
rows_=m.rows_;
cols_=m.cols_;
}
return *this;
}
Then in the main part of the program:
int main(){
Matrix m1(2,2);//creating a matrix of size 2x2
Matrix m2=m1; //this doesn't work
Matrix m3(m1); //nor this
return 0;
}
The error upon running the executable is: free(): double free detected in tcache 2
Am I correct in thinking that neither the copy constructor nor the assignment operator lead to the destructor being called? Why is that?