search

Home  >  Q&A  >  body text

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 days ago428

reply all(1)I'll reply

  • PHP中文网

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

    operator= You have not processed the previously allocated space and it may leak

    operator* To return Matrix, do not use new and then return. This is likely to cause memory leaks, such as:

    The caller forgot to release; the caller did not receive the return value;

    reply
    0
  • Cancelreply