【问题标题】:Using the copy-and-swap idiom, how does the destructor of the copied object not deallocate pointed to memory?使用复制和交换习语,复制对象的析构函数如何不取消分配指向内存?
【发布时间】:2015-04-26 21:55:06
【问题描述】:

我正在阅读以下问题:

What is the copy-and-swap idiom?

我的印象是,当一个对象通过值传递时,它的指针和值被复制,但传递的对象的指针指向的内存没有被复制。因此,当从链接到示例中重载赋值运算符时:

#include <algorithm> // std::copy
#include <cstddef> // std::size_t

class dumb_array
{
public:
    // (default) constructor
    dumb_array(std::size_t size = 0)
        : mSize(size),
          mArray(mSize ? new int[mSize]() : 0)
    {
    }

    // copy-constructor
    dumb_array(const dumb_array& other) 
        : mSize(other.mSize),
          mArray(mSize ? new int[mSize] : 0),
    {
        // note that this is non-throwing, because of the data
        // types being used; more attention to detail with regards
        // to exceptions must be given in a more general case, however
        std::copy(other.mArray, other.mArray + mSize, mArray);
    }

    // destructor
    ~dumb_array()
    {
        delete [] mArray;
    }

    friend void swap(dumb_array& first, dumb_array& second) // nothrow
    {
        // enable ADL (not necessary in our case, but good practice)
        using std::swap; 

        // by swapping the members of two classes,
        // the two classes are effectively swapped
        swap(first.mSize, second.mSize); 
        swap(first.mArray, second.mArray);
    }

    dumb_array& operator=(dumb_array other) // (1)
    {
        swap(*this, other); // (2)

        return *this;
    } 

private:
    std::size_t mSize;
    int* mArray;
};

...复制对象的析构函数如何不消除指向的资源mArray?正在完成分配的对象现在是否没有复制的mArray 指向可能已释放内存的指针? swap(first.mArray, second.mArray);这行是否分配了新的内存并复制了前一个数组的内容?

【问题讨论】:

  • dumb_array::dumb_array(const dumb_array&amp;) 是如何实现的?
  • 我将在整个示例类中进行编辑。您是否暗示在使用赋值运算符时调用了复制构造函数?我看不出它会在交换函数或重载赋值函数中使用。
  • 是的。现在把它放在一个自我回答而不是编辑中。 (或删除问题)。
  • 您已编辑以回答您自己的问题。 other 是一个(深)副本,因为它是按值传递并使用了您正确实现的副本构造函数。当operator= 返回时,other 被销毁,这将释放之前由*this 持有的资源。永远不会有两个对象共享相同的资源。

标签: c++ memory-management assignment-operator copy-and-swap


【解决方案1】:

随着您的复制构造函数的实现,

dumb_array(const dumb_array& other) 
        : mSize(other.mSize),
          mArray(mSize ? new int[mSize] : 0),

dumb_array 内部的mArray 被深度复制。不仅复制了指针,还创建了一个全新的数组并填充了std::copy() 的内容副本。

因此,当执行operator=(dumb_array other) 时,this-&gt;mArrayother.mArray(这是一个副本,因为参数是对象而不是引用)是两个不同的数组。在swap() 之后,other.mArray 持有原来由this-&gt;mArray 持有的指针。当operator=() 返回时,other.mArray 可以被~dumb_array() 删除。

【讨论】:

    猜你喜欢
    • 2017-02-23
    • 1970-01-01
    • 2013-08-10
    • 2011-10-28
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 2012-02-09
    • 2020-02-29
    相关资源
    最近更新 更多