suchen

Heim  >  Fragen und Antworten  >  Hauptteil

c++ - 请问这种写法会造成内存泄露吗?

Matrix::Matrix(int _row, int _col): row(_row), col(_col) {
    matrix = new double*[row];
    for (int i = 0; i < row; ++i) {
        matrix[i] = new double[col];
    }
}
Matrix::Matrix(const Matrix& m): row(m.row), col(m.col) {
    matrix = new double*[row];
    for (int i = 0; i < row; ++i) {
        matrix[i] = new double[col];
        for (int j = 0; j < col; ++j) {
            matrix[i][j] = m.matrix[i][j];
        }
    }
}
Matrix& Matrix::operator=(const Matrix& m) {
    row = m.row;
    col = m.col;
    matrix = new double*[row];
    for (int i = 0; i < row; ++i) {
        matrix[i] = new double[col];
        for (int j = 0; j < col; ++j) {
            matrix[i][j] = m.matrix[i][j];
        }
    }
    return *this;
}
Matrix::~Matrix() {
    for (int i = 0; i < row; ++i) {
        delete[] matrix[i];
    }
    delete[] matrix;
}
// 这个操作符重载这样写可以吗?//确实泄露了。。。我明白了
Matrix& Matrix::operator*(const Matrix& m) {
    Maples::assert((col == m.row), "Matrix Col != Row Error!");
    Matrix* result = new Matrix(row, m.col);
    double temp;
    for (int i = 0; i < row; ++i) {
        for (int j = 0; j < m.col; ++j) {
            temp = 0;
            for (int k = 0; k < col; ++k) {
                temp += (matrix[i][k] * m.matrix[k][j]);
            }
            result->matrix[i][j] = temp;
        }
    }
    return *result;
}
ringa_leeringa_lee2807 Tage vor429

Antworte allen(1)Ich werde antworten

  • PHP中文网

    PHP中文网2017-04-17 13:25:13

    operator= 你没有对之前分配的空间 进行 处理 ,可能 泄漏

    operator* 要返回 Matrix,不要new了然后返回,这样很可能会内存泄漏,比如:

    调用者忘记了释放; 调用者没有接收返回值;

    Antwort
    0
  • StornierenAntwort