C :Ostream无限递归

C++: ostream infinite recursion

本文关键字:递归 无限 Ostream      更新时间:2023-10-16

我以某种方式导致无限递归(以及最终的堆栈溢出)发生在此灾难中:

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。这是一个递归结构。我怀疑这对于矩阵确实是必要的。