【问题标题】:How to copy or return an object containing dynamically allocated memory?如何复制或返回包含动态分配内存的对象?
【发布时间】:2018-01-10 18:16:01
【问题描述】:

我有以下课程:

class Matrix {
    int *A;
    int m, n;
...
};
Matrix::Matrix(int rows, int cols){
    m = rows, n = cols;
    A = new int[m*n];
}
Matrix::~Matrix(){
    delete[] A;
}

我正在尝试编写一个返回 Matrix 对象的函数。这样做时,会调用默认的复制构造函数,这意味着每个新返回的对象都指向与函数中相同的动态分配内存块。这会导致程序表现不佳,因为当函数中的对象超出范围时,相同的内存会被释放。

我应该如何编写我的复制构造函数?有没有一种不需要我逐个元素复制 int 数组的解决方法?

如果有帮助,这里是函数:

Matrix Matrix::submatrix(int r, int c){
    if (m <= 1 || n <= 1)
        return Matrix(0, 0);    //return null matrix 

    Matrix T(m-1, n-1);

    int ti = 0; 
    for (int i = 0; i < m; i++){
        if (i == r) continue;
        for (int j = 0; j < n; j++){
            if (j == c) continue;

            T.A[ti] = this->valueAt(i, j);
            ti++;           
        }
    }
    return T;
}

【问题讨论】:

  • 您可能正在寻找移动构造函数和移动赋值运算符。您还应该阅读Return Value Optimization,它在某些情况下可以删除返回对象的副本。

标签: c++ object memory-management dynamic copy-constructor


【解决方案1】:

对于Matrix 类,您还必须添加一个复制构造函数和一个复制赋值运算符,以便以正确的方式使用动态分配的内存。

让我们从复制构造函数开始。基本版本可能如下所示:

Matrix::Matrix(const Matrix& other) {
    A = new int[other.m * other.n];
    std::copy(A, A + other.m * other.n, other.A);
}

您只需为A 分配内存,然后复制内容即可。

现在,复制赋值运算符:

Matrix& Matrix::operator=(const Matrix& other) {
    int* nA = new int[other.m * other.n];
    std::copy(nA, nA + other.m * other.n, other.A);

    delete[] A;
    A = nA;

    return *this;
}

这有点棘手。上面的代码为新矩阵分配内存,将内容复制到新分配的内存中并释放旧内存,然后更新A。它使用一个临时指针来处理可能抛出的new。

然后,您还可以添加移动构造函数和移动赋值运算符。

如前所述,首选方法是使用 STL 容器,例如 std::vector,它们自行管理内存。

【讨论】:

    【解决方案2】:

    由于您将矩阵有效地存储在一个大数组中,因此实现复制构造函数很简单:

    Matrix::Matrix(Matrix const& b) 
        : A(new int[b.m * b.n])
        , m(b.m), n(b.n)
    {
        std::copy_n(b.A, b.m * b.n, A);
    }
    

    您可能还想将数组存储在std::unique_ptr&lt;int[]&gt; 中,这样它就不会泄漏内存并防止您意外复制它。

    要实现复制分配,我建议使用swap:

    void Matrix::swap(Matrix& b) {
        using std::swap;
        swap(A, b.A);
        swap(m, b.m);
        swap(n, b.n);
    }
    
    Matrix& Matrix::operator=(Matrix const& b) {
        Matrix(b).swap(*this); // Re-use the copy constructor.
        return *this;
    }
    

    您可能还想以类似的方式实现移动构造函数和赋值:

    Matrix::Matrix(Matrix&& b)
        : A(b.A)
        , m(b.m), n(b.n)
    {
        b.A = nullptr;
    }
    
    Matrix::Matrix& operator=(Matrix&& b) {
        Matrix(std::move(b)).swap(*this); // Re-use the move constructor.
        return *this;
    }
    

    或者,将数组存储为std::vector&lt;int&gt;。这样编译器生成的复制构造函数、移动构造函数、赋值和析构函数为你做正确的事情。这也称为rule-of-zero。

    【讨论】:

    • 有什么理由使用 unique_ptr 而不是向量?如果不是,我认为矢量对我来说是最好的选择。
    • @DangerousTim std::vector&lt;&gt; 的大小是 std::unique_ptr&lt;&gt; 的 3 倍。如果您担心 CPU 缓存压力并且不使用 std::unique_ptr&lt;&gt; 调整向量的大小可能会导致代码更快。
    猜你喜欢
    • 2014-12-10
    • 2015-01-20
    • 2012-05-04
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 2016-07-10
    • 2018-09-06
    • 1970-01-01
    相关资源
    最近更新 更多