【发布时间】:2018-08-12 11:45:16
【问题描述】:
我正在尝试学习如何在 C++ 中分配内存。我按照这个答案分配二维数组:Copy 2D array using memcpy?
但是,当我尝试将其与使用 std::copy 复制内存相结合时,我遇到了损坏。
#include <iostream>
class Matrix
{
private:
int nrows;
int mcols;
double **entry;
public:
Matrix(int n, int m);
~Matrix();
Matrix& operator=(const Matrix& mat_in);
};
Matrix::Matrix(int n, int m)
{
nrows = n;
mcols = m;
std::cout << "Using regular constructor" << std::endl;
entry = new double*[nrows];
entry[0] = new double[nrows * mcols];
for(int i=1;i<nrows;i++)
entry[i] = entry[i-1] + mcols;
for(int i=0;i<nrows;i++)
for(int j=0;j<mcols;j++)
entry[i][j] = 0.0;
}
Matrix::~Matrix()
{
delete[] entry[0];
delete[] entry;
}
Matrix& Matrix::operator=(const Matrix& mat_in)
{
std::cout << "using deep copy constructor" << std::endl;
if(this == &mat_in)
return *this;
double **p = new double*[mat_in.nrows];
p[0] = new double[mat_in.nrows * mat_in.mcols];
std::copy(mat_in.entry, mat_in.entry + (mat_in.nrows * mat_in.mcols), p);
delete[] this -> entry;
entry = p;
nrows = mat_in.nrows;
mcols = mat_in.mcols;
return *this;
}
int main()
{
Matrix A(3,3);
Matrix B(3,3);
B = A;
return 0;
}
我认为问题在于我不完全理解当我释放内存并且我释放它两次时发生了什么。
【问题讨论】:
-
为什么你觉得需要一个指针数组(“二维数组”)?为什么单个
doubles 数组(大小为宽×高)不够用?这肯定会很多简单,然后你可能不会有这个问题。 -
考虑向book 学习。
-
考虑使用
std::array或std::vector而不是C 数组,以便赋值的工作方式与整数相同。它使事情变得容易得多。 -
请不要在现代 C++ 中使用手动内存管理。使用容器和智能指针以及 RAII..
-
@JohnMeighan 同样的问题也适用于 C.
标签: c++