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;
}
}
如果我取消()循环并删除初始cout的末端,则该功能正常。因此,我认为它是由超载&lt;&lt;引起的。操作员:
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
destructor中调用operator<<
时,您会导致递归环。
您应该尽可能避免通过值传递函数参数。避免制作不必要的副本,这会减慢您的程序,因为它会生成额外的代码(在这种情况下,是复制构造函数和destructor)。
将您对operator<<
的定义更改为从一开始应该是什么:
ostream &operator<<(ostream &output, const MyMatrix &a);
旁注:从您显示的代码中,您似乎有一个包含Matrix*
的Matrix
。这是一个递归结构。我怀疑这对于矩阵确实是必要的。
相关文章:
- 交换运算符 + 重载会导致无限递归
- 为什么当函数参数未定义为常量引用时存在无限递归?
- 递归应用 C++20 范围适配器会导致编译时无限循环
- 为什么这个递归函数会创建一个无限循环?
- 计算递归和时的无限循环
- 为什么这是无限递归
- C 递归函数无限循环
- 尝试"复制"shared_ptr向上转换行为会导致复制构造函数上的无限递归(导致段错误)
- ConstexPR模板功能的无限递归
- 交换和移动无限递归
- 无限循环与无限递归.两者都未定义吗?
- 函数中的无限递归
- 无限模板递归,因为没有布尔表达式优化,只有 gcc
- 运算符重载流提取运算符 (>>) C++会导致无限递归流提取
- C 无限环路:递归函数
- 实现递归函数,避免由 C++ 中 include 的循环调用(没有 #pragma 一次)引起的无限循环输入
- C :Ostream无限递归
- 无限递归模板实例化使用clang时GCC工作正常
- 当我使用 boost 构建绝对路径时,无限递归
- 模板中的无限递归