c bad_array_new_length通过返回语句抛出

C++ bad_array_new_length exception thrown by return statement?

本文关键字:返回 语句 length bad array new      更新时间:2023-10-16

我在一周的过程中一直在做矩阵类,并且遇到了一个让我困惑的问题:我的一个功能的返回语句是抛出bad_array_new_new_length exception!

这是我用来查找的示例代码:

Matrix Matrix::operator*(Matrix& mat)
{
    if (this->columns != mat.rows)
    {
        //Do code if Matrix can't be multiplied.
    }
    else
    {
        Matrix result(this->rows, mat.columns);
        //Multiply Matrices together.
        //Print out result to prove the local Matrix works fine.
        //It does.
        try
        {
            return result;
        }
        catch (const exception& e)
        {
            cout << "return exception: " << e.what() << endl;
            return result;  //To be caught again in the test.
        }
    }
}

低,看,当我运行功能时,它将打印出"返回异常:bad_array_new_length"到控制台。

该功能像这样测试:

try
{
    answer = A1 * B1;   //A1 and B1 are able to be multiplied.
}
catch (const exception& e)
{
    cout << e.what() << endl;
}

测试还捕获了例外并将其打印出来。

进行了一些研究后,只有在给出无效的长度时,就会抛出BAD_ARRAY_NEW_LENGTH例外。矩阵类的确使用多维阵列来存储双打,但我认为这不是问题的根源,因为本地矩阵按预期的是完美。

这是在构造函数中声明和初始化多维数组的方式,以防万一:

//Matrix.h
unsigned int rows;
unsigned int columns;
double ** storage = new double*[rows];  //Multidimensional array isn't completely formed, see the constructor.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Matrix.cpp
Matrix::Matrix(unsigned int x, unsigned int y)
:
    rows(x),
    columns(y)
{
    for (unsigned int i = 0; i < rows; ++i) //Completes the formation of the multidimensional array.
        storage[i] = new double[columns];
    for (unsigned int i = 0; i < rows; ++i)
    {
        for (unsigned int q = 0; q < columns; ++q)
        {
            storage[i][q] = 0;  //Initializes each value in the array as 0.
        }
    }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

编辑:

这是定义的复制构造函数和分配运算符:

Matrix::Matrix(const Matrix& obj)
{
    rows = obj.rows;
    columns = obj.columns;
    for (unsigned int i = 0; i < rows; ++i)
    {
        for (unsigned int q = 0; q < columns; ++q)
        {
            storage[i][q] = obj.storage[i][q];
        }
    }
}
////////////////////////////////////////////////////////////////////////////////
bool Matrix::operator=(Matrix mat)
{
    rows = mat.rows;
    columns = mat.columns;
    for (unsigned int i = 0; i < rows; ++i)
    {
        for (unsigned int q = 0; q < columns; ++q)
        {
            storage[i][q] = mat.storage[i][q];
        }
    }
    return true;
}

出于好奇,我将测试中的代码更改为:

try
{
    A1 * B1;    //Removed assignment to answer Matrix.
}
catch (const exception& e)
{
    cout << e.what() << endl;
}

..,例外仍然像正常一样。

解决了问题,我要做的只是在类声明和构造函数中分配内存的方式。