重载operator =中的内存泄漏

Mum*_*wiz 0 c++ memory memory-leaks memory-management

我有这个矩阵的构造函数来分配内存

class Matrix 
{

public:
    int** matrix;
    int cols;
    int rows;
};
Matrix::Matrix(int row, int col)
{
    cols = col;
    rows = row;
    matrix = new int*[rows];
    int i;
    for (i = 0; i < rows; ++i)
    {
        matrix[i] = new int[cols];
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想重载operator =,但我无法弄清楚如何编写函数并分配新内存,而不会导致内存泄漏或内存不足.

我要做的矩阵=在它上面,已经为它分配了内存,那么我可以删除内存并使另一个内存大小的新内存吗?

现在我在operator =上有这个

this->rows = other.rows;
this->cols = other.cols;

int i, j;
for (i = 0; i < this->rows; ++i)
{
    for (j = 0; j < this->cols; j++)
    {
        this->matrix[i][j] = other.matrix[i][j];
    }

}
return *this;
Run Code Online (Sandbox Code Playgroud)

Cap*_*ffe 5

惯用的方法是使用复制/交换习语.请参阅什么是复制和交换习惯用法?

然后,分配减少到

Matrix& operator=(Matrix copy){
   swap(*this, copy);
   return *this;
}
Run Code Online (Sandbox Code Playgroud)

使用此习语查看您获得的所有津贴的链接问题.