重载操作符内存泄漏=
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];
}
}
现在我想重载操作符=,但是我不知道如何编写函数并分配新的内存,而不会出现内存泄漏,或者没有足够的内存。
矩阵,我将在它上面做=,已经为它分配了内存,所以我可以删除内存并在另一个的大小上创建新内存吗?
现在我有这个运算符=
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;
之后,您可以根据需要从作为参数传递的矩阵分配新矩阵。
相关文章:
- C++功能泄漏内存,我是C++新手,不确定如何解决
- 我的堆栈弹出式磁带的实现是否泄漏内存?
- 将 c++ 向量转换为字符 ** 而不会泄漏内存
- 析构函数 C++ 使泄漏内存
- 构造函数对象赋值是否泄漏内存
- corba :: orb_init泄漏内存
- Gmock泄漏内存
- 如何在不泄漏内存的情况下删除链接列表
- Visual C ODBC关闭记录集泄漏内存
- 为什么泄漏内存比在动态数组上执行 delete[] 慢
- OpenGL正在泄漏内存.哪个对象未释放
- 可以std ::退出泄漏内存
- uiautomation findall泄漏内存
- 为什么在此OpenCL代码中泄漏内存,为什么要泄漏内存
- pthread在完成后会泄漏内存
- win32 标准::线程泄漏内存
- 返回指向同一变量的指针是否会泄漏内存
- 使用clectType(new any_type())可能会泄漏内存泄漏
- Windows开发:如何确定我的应用程序是否正在泄漏内存
- WinHttp打开泄漏内存