c++空复制赋值运算符复制数据



我对c++有点陌生,想写一个小矩阵库,它有一个基类Matrix,其中有一些新的矩阵类型,如SparseMatrixDenseMatrixHashMatrix等。

我的基类是这样的:


class Matrix {

protected:
int m,n;

public:


Matrix(int m_p, int n_p) : m(m_p), n(n_p){
std::cout << "gen constr" << std::endl;
}
Matrix(Matrix& other) = delete;
Matrix() = delete;

virtual ~Matrix() {}

int getM() const {
return m;
}
int getN() const {
return n;
}
virtual double& get(int m, int n) = 0;
virtual double  get(int m, int n) const = 0;
inline double& operator() (int m, int n){
return get(m,n);
}
inline double  operator() (int m, int n) const{
return get(m,n);
}
friend std::ostream &operator<<(std::ostream &os, Matrix &matrix) {
using std::scientific;
using std::fixed;
os << std::fixed << std::setprecision(2) << scientific << std::setfill(' ');
for(int i = 1; i <= matrix.getM(); i++){
for(int j = 1; j <= matrix.getN(); j++){
os << std::setw(10) << matrix.get(i,j)  << " ";
}
os << "n";
}
return os;
}


Matrix& operator=(const Matrix& other) {
//        std::cout << "equality assign" << std::endl;
return *this;
}
};

正如您所看到的,我已经覆盖了相等赋值运算符,它只是返回对象,实际上并不复制值。

我对DenseMatrix的第一个实现非常直接:

class DenseMatrix : public Matrix{

private:
double* data;
public:

DenseMatrix(int mP, int nP) : Matrix(mP, nP){
std::cout << "gen constr base" << std::endl;
this->data = new double[mP * nP]{0};
}




DenseMatrix() = delete;
~DenseMatrix() {
delete this->data ;
}
double &get(int m, int n) {
int index = m*getN()+n-(getN()+1);
assert(index < (getN() * getM()) && index >= 0);
return this->data [index];
}
double get(int m, int n)const {
int index = m*getN()+n-(getN()+1);
assert(index < (getN() * getM()) && index >= 0);
return this->data [index];
}


};

此外,main()函数如下所示:

DenseMatrix mat(3,3);
for(int i = 1; i<= 3; i++){
mat(i,i) = i;
}

DenseMatrix mat2(3,3);
mat2 = mat;


std::cout << mat << std::endl;
std::cout << mat2 << std::endl;

>>>  1.00e+00   0.00e+00   0.00e+00 
>>>  0.00e+00   2.00e+00   0.00e+00 
>>>  0.00e+00   0.00e+00   3.00e+00 
>>>  1.00e+00   0.00e+00   0.00e+00 
>>>  0.00e+00   2.00e+00   0.00e+00 
>>>  0.00e+00   0.00e+00   3.00e+00 

正如你所看到的,我首先创建了两个矩阵。我调整第一个矩阵的值,并将第二个矩阵的默认值保留为0。然而,在调用相等赋值运算符后,即使我实现的函数基本上没有影响矩阵的代码,第二个矩阵的内容也会发生变化。

我不理解这种行为,如果有人能简要解释一下这里发生了什么,我会非常高兴。

非常感谢您的耐心和帮助:(

您尚未删除或定义DenseMatrixoperator=复制赋值运算符,因此编译器将为您合成一个。此函数将执行数据成员的成员复制,在本例中为double *data。由于指针将指向matmat2中的相同内容,因此在打印它们时会看到相同的内容。

请注意,这可能不是您想要的。一个问题是,您的DenseMatrix析构函数将两次转到deletedata,这可能会导致segfault。

您没有为DenseMatrix定义赋值运算符。

隐式生成的赋值运算符分配子对象。基本子对象将使用Matrix的重载赋值运算符进行赋值,因此存储在基本子对象中的标注不会被修改,但您已将标注指定为相同的标注,因此它们无论如何都会被赋值为相同的值。

最新更新