未调用析构函数,程序异常退出时出现问题

Destructor not called and issue with program exiting abnormally

本文关键字:问题 退出 异常 调用 析构函数 程序      更新时间:2023-10-16

我有以下代码来定义类Matrix。头文件中的定义如下:

#ifndef MATRIX_H
#define MATRIX_H
/* General matrix class */
class Matrix
{
    public:
        Matrix(int m, int n, double ini);
        virtual ~Matrix();
        Matrix(const Matrix& other); //copy ctor
        Matrix& operator=(const Matrix& other); //assignment operator;
        double operator()(int i, int j) const; //access element in the matrix
        double& operator() (int i, int j); //set element in the matrix
        friend Matrix operator+(const Matrix& mat1, const Matrix& mat2); //Matrix addition
        friend Matrix operator+(const Matrix& mat1, double a); //scaler multiplication
        int dimension() const {return rows*cols;} //getter method for dimension
    protected:
    private:
        int rows; //number of rows in the matrix
        int cols; //number of cols in the matrix
        double* d; //pointer to the representation of the matrix
};

与该问题有关的部分的执行情况如下所示。

#include "Matrix.h"
#include<iostream>
Matrix::Matrix(int m, int n, double ini):rows{m},cols{n},d{new double[m*n]}
{
        //ctor
        double* p = d;
        for(int i=0;i<rows*cols;i++)
        {
            *p++ = ini;
        }
}
Matrix::~Matrix()
{
    //dtor
    delete []d;
}

Matrix& Matrix::operator=(const Matrix& rhs)
{
    if (this == &rhs) return *this; // handle self assignment
    if (rows*cols<=rhs.rows*rhs.cols)
    {
        delete []d;
        d = new double[rhs.rows*rhs.cols];
        rows = rhs.rows;
        cols = rhs.cols;
        for(int i=0;i<rows*cols;i++)
        {
            d[i] = rhs.d[i];
        }
    }
    //assignment operator
    return *this;
}
double Matrix::operator()(int i, int j) const
{
    return d[rows*i + j];
}
double& Matrix::operator()(int i, int j)
{
    return d[rows*i+j];
}

现在,我有一个简单的测试应用程序,它创建一个矩阵,为矩阵中的元素赋值,并读取元素的值(给定行和列编号)。

    #include <iostream>
    #include "Matrix.h"
    using namespace std;
    int main()
    {
        int i,j;
        Matrix A(3,2,0.0);
        cout<<A.dimension()<<endl;
    // assign values to matrix elements
        for (i=0;i<3;i++)
            {
                for (j=0;j<2;j++) A(i,j) = 0.1*i*j;
            }
            // access matrix elements
        double sum = 0.0;
        for (i=0;i<3;i++) {
            for (j=0;j<2;j++) sum += A(i,j); }
        cout << "The sum of the matrix elements is ";
        cout << sum << endl;
        return 0;
    }

我的问题是,虽然所有的编译都没有问题,但当运行时,主函数会冻结——不过上面的"总和"是计算出来的。想知道这是因为析构函数没有被调用还是无法被调用。如果有人有任何想法,我将不胜感激。

我认为您的代码在operator()中是错误的

double Matrix::operator()(int i, int j) const
{
    return d[cols*i + j];
}
double& Matrix::operator()(int i, int j)
{
    return d[cols*i+j];
}

并且溢出数组d[]