c++ - 请问这种写法会造成内存泄露吗?
ringa_lee
ringa_lee 2017-04-17 13:23:13
0
1
417
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_lee
ringa_lee

ringa_lee

reply all(1)
Ty80

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;

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template