删除数组时断言失败

Assertion failed when deleteing array

本文关键字:失败 断言 数组 删除      更新时间:2023-10-16

我的框架类中有一个析构函数,它执行:

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

附带说明一下,无需在析构函数中重置widthheight。销毁对象后,无法访问这些字段。

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;
}