调试断言失败错误

Debug Assertion Failed error

本文关键字:错误 失败 断言 调试      更新时间:2023-10-16

我试图为我正在做的项目重载+运算符,但这种情况一直在发生。我认为原因是当调用操作符时,我创建的对象被删除了。但不知道如何修复。这是我的部分代码:

Matrix Matrix::operator+ (const Matrix& m) const
{
    //something wrong here
    Matrix sum(rows, cols);
    for (int i = 0; i < cols; i++)
    {
        for (int j = 0; j < rows; j++)
        {
            sum.element[i][j] = this->element[i][j] + m.element[i][j];
        }
    }
    return sum;
}

附加信息

Matrix::Matrix(int r, int c)
{
    rows = r;
    cols = c;
    element = new int *[c];
    for (int i = 0; i < c; i++)
    {
        element[i] = new int[r];
    }
    for (int i = 0; i < cols; i++)
    {
        for (int j = 0; j < rows; j++)
        {
            element[i][j] = 0;
        }
    }
}

Matrix::Matrix(const Matrix& m)
{
    this->element = m.element;
}

Matrix::~Matrix()
{
    //freeing up the arrays
    for (int i = 0; i < cols; i++)
    {
        delete[] element[i];
        element[i] = NULL;
    }
    delete[] element;
    element = NULL;
}

Matrix& Matrix::operator= (const Matrix& m)
{
    //problem if rows and cols are longer in the new matrix
    //need to create a temp matrix to expand to new one
    for (int i = 0; i < cols; i++)
    {
        for (int j = 0; j < rows; j++)
        {
            this->element[i][j] = m.element[i][j];
        }
    }
    return *this;
}

int* Matrix::operator[] (int n)
{
    return element[n];
}

我得到的具体错误是:

调试断言失败!

表达式:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

在我做的第52行:

 Matrix total = mat + m;

其中mat和m都是对象矩阵

我猜问题是由以下原因引起的:

Matrix::Matrix(const Matrix& m)
{
    this->element = m.element;
}

这是一个无效的复制构造函数,原因有二。首先,您没有初始化rowscols。第二,现在有两个指向同一内存的Matrix对象,这两个对象在销毁时都会删除它:

{
    Matrix m1(3, 5);
    Matrix m2 = m1;
} // BOOM!

你需要在这里做一个深度复制:

Matrix::Matrix(const Matrix& m)
: rows(m.rows), cols(m.cols)
{
    element = new int *[cols];
    for (int i = 0; i < cols; ++i) {
        element[i] = new int[rows];
        for (int j = 0; j < rows; ++j) {
            element[i][j] = m.element[i][j];
        }
    } 
}
相关文章: