[英]memory leak in overloading operator =
我有这个构造函数供矩阵分配内存
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];
}
}
现在,我想重载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;
惯用的方法是使用复制/交换惯用法。 请参阅什么是复制和交换惯用法?
然后将分配减少为
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;
之后,您可以根据需要从作为参数传递的矩阵中分配新矩阵。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.