C++:ostream无限递归
C++: ostream infinite recursion
我以某种方式导致此析构函数内部发生无限递归(以及最终的堆栈溢出):
MyMatrix::~MyMatrix() {
if (this != NULL) {
cout << "Destructor called for " << this->matrix << ":" << endl << *this << endl;
/*for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}*/
delete[] *matrix;
delete[] matrix;
}
}
如果我取消对 for() 循环的注释并删除初始 cout 的末尾,该函数可以正常工作。因此,我认为它是由重载的 << operator:
引起的
ostream &operator<<(ostream &output, MyMatrix a)
{
if (&a != NULL) {
for (int i = 0; i < a.m; i++) {
for (int j = 0; j < a.n; j++) {
output << a.matrix[i][j] << " ";
}
output << endl;
}
}
return output;
}
编辑:
这是构造函数
MyMatrix::MyMatrix(int i_m, int i_n) {
m = i_m;
n = i_n;
if (n < 1 || m < 1)
throw string("Dimensions cannot be negative");
matrix = new float*[m];
for (int i = 0; i < m; i++) {
matrix[i] = new float[n];
for (int j = 0; j < n; j++)
matrix[i][j] = 0;
}
}
问题出在你的operator<<
声明中:
ostream &operator<<(ostream &output, MyMatrix a);
您正在按值传递 a
。这会导致对传递的 Matrix
进行临时复制,并在 operator<<
退出时销毁该副本。当您在 Matrix
析构函数中调用 operator<<
时,会导致递归循环。
您应该尽可能避免按值传递函数参数。避免进行不必要的复制,这会减慢您的程序,因为它会生成额外的代码(在本例中,复制构造函数和析构函数)。
将您对 operator<<
的定义更改为从一开始就应有的定义:
ostream &operator<<(ostream &output, const MyMatrix &a);
旁注:从您显示的代码来看,您似乎有一个包含 Matrix*
的 Matrix
。这是一个递归结构。我怀疑这对于矩阵是否真的有必要。
我以某种方式导致此析构函数内部发生无限递归(以及最终的堆栈溢出):
MyMatrix::~MyMatrix() {
if (this != NULL) {
cout << "Destructor called for " << this->matrix << ":" << endl << *this << endl;
/*for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}*/
delete[] *matrix;
delete[] matrix;
}
}
如果我取消对 for() 循环的注释并删除初始 cout 的末尾,该函数可以正常工作。因此,我认为它是由重载的 << operator:
引起的ostream &operator<<(ostream &output, MyMatrix a)
{
if (&a != NULL) {
for (int i = 0; i < a.m; i++) {
for (int j = 0; j < a.n; j++) {
output << a.matrix[i][j] << " ";
}
output << endl;
}
}
return output;
}
编辑: 这是构造函数
MyMatrix::MyMatrix(int i_m, int i_n) {
m = i_m;
n = i_n;
if (n < 1 || m < 1)
throw string("Dimensions cannot be negative");
matrix = new float*[m];
for (int i = 0; i < m; i++) {
matrix[i] = new float[n];
for (int j = 0; j < n; j++)
matrix[i][j] = 0;
}
}
问题出在你的operator<<
声明中:
ostream &operator<<(ostream &output, MyMatrix a);
您正在按值传递 a
。这会导致对传递的 Matrix
进行临时复制,并在 operator<<
退出时销毁该副本。当您在 Matrix
析构函数中调用 operator<<
时,会导致递归循环。
您应该尽可能避免按值传递函数参数。避免进行不必要的复制,这会减慢您的程序,因为它会生成额外的代码(在本例中,复制构造函数和析构函数)。
将您对 operator<<
的定义更改为从一开始就应有的定义:
ostream &operator<<(ostream &output, const MyMatrix &a);
旁注:从您显示的代码来看,您似乎有一个包含 Matrix*
的 Matrix
。这是一个递归结构。我怀疑这对于矩阵是否真的有必要。