c bad_array_new_length通过返回语句抛出
C++ bad_array_new_length exception thrown by return statement?
我在一周的过程中一直在做矩阵类,并且遇到了一个让我困惑的问题:我的一个功能的返回语句是抛出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;
}
..,例外仍然像正常一样。
解决了问题,我要做的只是在类声明和构造函数中分配内存的方式。
相关文章:
- 返回语句后的代码,没有警告
- 三元运算符在返回语句中给出意外的结果
- 返回非 void 的函数中没有返回语句警告
- 如何使用单个返回语句返回对变量的引用
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 获取上次执行的返回语句的行
- 返回语句中矢量初始化时出现编译错误
- 快速搜索链表未编译,需要返回语句
- 静态成员函数赋值而不带返回语句
- 在返回语句中构造对象时,std::move() 是否有助于或阻止 RVO?
- 为什么返回语句和打印语句返回不同的答案?
- C++ 非 void 函数的崩溃没有返回语句
- 在返回语句中嵌套条件运算符
- 为什么结构化绑定禁用RVO和移动返回语句
- C - 程序返回值而无需返回语句
- 返回语句中的构造函数语法
- 编译器遇到返回语句时会做什么
- 是一个单一的返回语句清洁器
- C NRVO/复制Elision在括号中带有返回语句
- C 编译器 - 被遗忘的返回语句