删除数组时断言失败
Assertion failed when deleteing array
我的框架类中有一个析构函数,它执行:
delete this->frameMatrix;
其中帧矩阵是类矩阵,它作为构造函数和析构函数:
// Constructor: Initialize matrix & sizes
Matrix::Matrix(int width, int height)
{
table = new double* [height];
for(int i = 0; i < height; i++)
table[i] = new double [width];
// Set all values to zero
for(int row = 0; row < height; row++)
{
for(int col = 0; col < width; col++)
{
table[row][col] = 0;
}
}
this->width = width;
this->height = height;
}
// Destructor: delete matrix
Matrix::~Matrix()
{
for(int row = 0; row < height; row++)
delete [] table[row];
delete [] table;
this->width = 0;
this->height = 0;
}
在 frameMatrix 上调用删除时,程序在矩阵析构函数中给出一个断言失败。
我做错了什么,因为我没有看到如何删除 2d 双数组的问题。
编辑:
复制构造函数:
Matrix::Matrix(const Matrix &m)
{
this->height = m.getHeight();
this->width = m.getWidth();
this->table = new double* [height];
for(int i = 0; i < height; i++)
this->table[i] = new double [width];
for(int row = 0; row < height; row++)
{
for(int col = 0; col < width; col++)
{
this->table[row][col] = m.table[row][col];
}
}
}
我的超载 =
Matrix &operator = (const Matrix &m)
{
this->height = m.getHeight();
this->width = m.getWidth();
this->table = new double* [height];
for(int i = 0; i < height; i++)
this->table[i] = new double [width];
for(int row = 0; row < height; row++)
{
for(int col = 0; col < width; col++)
{
this->table[row][col] = m.table[row][col];
}
}
}
你有复制构造函数和operator=
吗?您需要重写这些方法的默认实现,因为您已经动态分配了指针。
class Matrix
{
public:
Matrix(const Matrix &);
Matrix &operator = (const Matrix &);
};
如果没有它们,无论何时复制Matrix
对象,新对象将具有与原始对象相同的指针。析构函数最终将对数组进行双重delete
。
附带说明一下,无需在析构函数中重置width
和height
。销毁对象后,无法访问这些字段。
this->width = 0;
this->height = 0;
赋值运算符的样板代码:
Matrix &operator = (const Matrix &m)
{
// Don't do anything for `m = m;`.
if (&m == this)
return *this;
// Delete existing contents.
...
// Copy other matrix.
...
return *this;
}
相关文章:
- 尝试使用 std::vector<std::thread时出现静态断言失败错误>
- uint_not_usable_without_attribute在业力规则中使用数字生成器时静态断言失败
- 从 exe 文件 (Visual Studio ) 启动时调试断言失败
- 断言"id < 0"在Qt ActiveX中失败
- 在 CppUnit 中测试中止断言失败
- 使用扫描的调试断言失败
- MS 本机单元测试 - 断言::线程失败不起作用
- 为什么我的Qt程序在断言失败后继续运行?
- 图片不显示,关闭时出错 --> 调试断言失败!表达式:is_block_type_valid(标头>_block_use)
- 访问提升:shared_ptr 主范围外崩溃,断言失败:px != 0.指针的正确用法是什么?
- C++ 调试断言失败 - 矢量下标超出视觉工作室的范围
- 错误:断言失败 (src.type() == CV_8UC1) 在阈值中
- Boost Beast 异步服务器失败,断言失败:(id_ != T::id) 在多个 aync 调用中
- 使用imwrite OpenCV时断言失败
- 调试断言失败的缓冲区!=nullptr
- 使用 ofstream 写入文本文件时断言失败
- OpenCV 错误:相机校准:断言在matrix_wrap.cpp失败
- 提升继续恢复断言失败
- 获取有关调试断言失败的错误:表达式:"(_Ptr_user &(_BIG_ALLOCATION_ALIGNMENT -1)) == 0" &&0
- 打破gdb中失败断言的正确方法是什么