c++ - How to correctly specify the copy constructor -
assume have class matrix, constructor follows:
matrix::matrix(int rows, int cols) { nrows = a; //here nrows number of rows each matrix ncols = b; //here ncols number of cols each matrix p = new double [rows*cols]; for(int i=0;i<rows*cols;i++) { *p++ = 0.0; } }
suppose have 'copy' constructor 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 have following lines in main function:
int main() { matrix a(2,2); matrix b(2,2); = matrix(b); //call overloaded assignment operator, , copy ctor/ }
here '=' operator overloaded assign elements in b a. issue once call copy constructor made, matrix object new object.
is there better way of writing copy constructor if matrix exists calling = matrix(b) results in error?
instead of using dynamically allocated arrays, recommend using std::vector
class matrix { public: matrix(long rows, long cols); private: long nrows; long ncols; std::vector<double> p; }
then constructor can be
matrix::matrix(long rows, long cols) : nrows(rows), ncols(cols), p(rows * cols) { }
along all of other benefits of using std::vector
on dynamically allocated arrays, compiler-generated copy constructor, don't need write one.
if don't want class copyable, delete
copy constructor , 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; }
Comments
Post a Comment