重载操作符内存泄漏=

memory leak in overloading operator =

本文关键字:泄漏 内存 操作符 重载      更新时间:2023-10-16

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

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];
    }
}

现在我想重载操作符=,但是我不知道如何编写函数并分配新的内存,而不会出现内存泄漏,或者没有足够的内存。

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

现在我有这个运算符=

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;

习惯的方法是使用复制/交换习惯用法。参见什么是复制和交换习语?

然后赋值化为

Matrix& operator=(Matrix copy){
   swap(*this, copy);
   return *this;
}

请参阅链接问题,了解使用这个习语所获得的所有好处。

我建议从手动分配数组切换到使用std::vector

class Matrix 
{
public:
    Matrix(int row, int col);
    int cols;
    int rows;
    std::vector<std::vector<int>> matrix;
};
Matrix::Matrix(int row, int col)
:  cols(col),
   rows(row),
   matrix(rows, std::vector<int>(cols))
{ }

现在可以让编译器生成复制赋值操作符,以及其他构造函数、析构函数等。这个类现在是可复制的,可移动的,并且不会泄漏内存,因为matrix现在使用RAII语义而不是你必须管理它的内存。

首先可以使用delete操作符重新分配每个列。

for (i = 0; i < rows; ++i)
    {
           delete []matrix[i];
    }

然后可以释放指向每一行的指针。

 delete []matrix;

之后,您可以根据需要从作为参数传递的矩阵分配新矩阵。