删除数组时断言失败

时间:2012-11-28 00:02:15

标签: c++

我的框架类中有一个析构函数:

delete this->frameMatrix; 

其中framematrix属于Matrix类,其中包含构造函数和析构函数:

// 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上调用delete时,程序在矩阵的析构函数中给出一个断言失败。

我正在做错事,因为我没有看到如何删除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];
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

你有一个复制构造函数和operator=吗?您需要覆盖这些方法的默认实现,因为您已经获得了动态分配的指针。

class Matrix
{
public:
    Matrix(const Matrix &);
    Matrix &operator = (const Matrix &);
};

没有它们,只要复制Matrix对象,新对象将具有与原始对象相同的指针。析构函数最终会加倍 - delete数组。

在旁注中,无需在析构函数中重置widthheight。在销毁对象后,这些字段无法访问。

<击>

<击>
this->width = 0;
this->height = 0;

<击>


赋值运算符的Boilerplate代码:

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