How to specify copy constructor correctly

Suppose I have a Matrix class, with a constructor as follows:

Matrix::Matrix(int rows, int cols) { nrows = a; //here nrows is the number of rows for each matrix ncols = b; //here ncols is the number of cols for each matrix p = new double [rows*cols]; for(int i=0;i<rows*cols;i++) { *p++ = 0.0; } } 

Suppose I also have a copy constructor as follows:

 Matrix::Matrix(const Matrix& mat) { p = new double[mat.nrows*mat.ncols]; for(int i=0;i<mat.nrows*mat.ncols;i++) { p[i] = mat.p[i]; } } 

Now suppose I have the following lines in my main function:

 int main() { Matrix A(2,2); Matrix B(2,2); A = Matrix(B); //call overloaded assignment operator, and copy ctor/ } 

Here the '=' operator is overloaded to assign all the elements from B to A. My problem is that after calling the copy constructor, the Matrix A object is a completely new object.

Is there a better way to write a copy constructor so that if matrix A already exists, then calling A = Matrix (B) leads to an error?

+4
source share
4 answers

Instead of using dynamically allocated arrays, I would recommend using std::vector

 class Matrix { public: Matrix(long rows, long cols); private: long nrows; long ncols; std::vector<double> p; } 

Then your constructor may be

 Matrix::Matrix(long rows, long cols) : nrows(rows), ncols(cols), p(rows * cols) { } 

Along with all the other benefits of using std::vector for dynamically allocated arrays, you now get a copy constructor created by the compiler, so you don't need to write it.

If you do not want your class to be copyable, delete the copy constructor and copy assignment operator.

 class Matrix { public: Matrix(long rows, long cols); Matrix(const Matrix& mat) = delete; Matrix& operator=(const Matrix& mat) = delete; private: long nrows; long ncols; std::vector<double> p; } 
+8
source

With approval

 A = Matrix(B); 

First, a temporary object is created using the copy constructor. This temporary object is then used in assignment.

So, itโ€™s true that a copy constructor is used, but not as part of the assignment.

+3
source

It would be much better to remove the assignment operator:

Matrix& operator=(const Matrix&) = delete;

Then using A = Matrix(B) will result in a compile-time error. Then you have to use the constructor, and your specific problem will cease to be relevant.

+2
source

Not. Because then it will not be a copy constructor. Constructors of constructors.

0
source

All Articles