调试断言失败错误
Debug Assertion Failed error
我试图为我正在做的项目重载+运算符,但这种情况一直在发生。我认为原因是当调用操作符时,我创建的对象被删除了。但不知道如何修复。这是我的部分代码:
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;
}
这是一个无效的复制构造函数,原因有二。首先,您没有初始化rows
或cols
。第二,现在有两个指向同一内存的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];
}
}
}
相关文章:
- 尝试使用 std::vector<std::thread时出现静态断言失败错误>
- Websocket++ 错误:收到错误handle_transport_init TLS 握手失败
- Netbeans 10:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- 这个失败的测试是将零添加到空指针未定义的行为、编译器错误还是其他什么?
- 构建失败错误:无法使用 qibuild 构建C++ SDK Helloworld
- q网络回复 无状态码或错误,但失败
- 创建服务失败0x6f7存根收到错误数据
- 两个线程一个使用流 Api,另一个线程创建文件失败并出现错误ERROR_SHARING_VIOLATION
- CMake 错误:链接器命令失败,退出代码为 1 和 cpp.o 文件
- clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用) - 体系结构的未定义符号 x86_64:
- 调试模板时出现问题.专门针对 Linux GCC 7、GCC 6、GCC 5、GCC 4.9 错误构建失败:模板参数 1
- 如何修复 clang: 错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- 错误:断言失败 (src.type() == CV_8UC1) 在阈值中
- 失败,出现错误 87:参数不正确.如何判断哪个参数不正确?
- 创建进程 API 失败,在窗口 122 上出现错误代码 10
- 加速兽握手:sslv3 警报握手失败错误
- 自定义预期失败的完整错误消息(boost::spirit::x3)
- 从 Linux OMI (omicli) 到 Windows WMI 的连接失败,并出现与 DMTF 相关的错误
- libcurl错误失败的写作已接收到磁盘/应用程序的数据
- std::timed_mutex::try_lock*错误失败