1

フレームクラスに次のようなデストラクタがあります。

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を呼び出すと、プログラムはmatrixのデストラクタで失敗したアサーションを返します。

2d double配列を削除する方法に問題がないため、何か間違ったことをしています。

編集:

コピーコンストラクター:

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

1 に答える 1

2

コピーコンストラクターはありoperator=ますか?動的に割り当てられたポインターがあるため、これらのメソッドのデフォルトの実装をオーバーライドする必要があります。

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

それらがないと、オブジェクトがコピーされるたびにMatrix、新しいオブジェクトは元のオブジェクトと同じポインタを持ちます。デストラクタは、最終delete的にアレイを2倍にします。

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;
}
于 2012-11-28T00:05:22.597 に答える