c++ - 使用 copy-and-swap 惯用语,复制对象的析构函数如何不释放指向内存?

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

我正在阅读以下问题:

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(const dumb_array& other) 
        : mSize(other.mSize),
          mArray(mSize ? new int[mSize] : 0),

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

因此,当 operator=(dumb_array other) 被执行时,this->mArrayother.mArray (这是自参数是对象而不是引用)是两个不同的数组。在swap()之后,other.mArray保存着原先由this->mArray保存的指针。当 operator=() 返回时,other.mArray 可以被 ~dumb_array() 删除。

关于c++ - 使用 copy-and-swap 惯用语,复制对象的析构函数如何不释放指向内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28709980/

相关文章:

java - 自增运算符++

c++ - 使用OpenCV进行条纹布检测

c++ - 当我希望调用基类构造函数时,如何在派生类中初始化成员 const 引用?

c++ - C++ 概念的通配符为 "accepting anything for this template argument"

c++ - 如何在没有轮询的情况下实现 std::when_any?

iphone - 在二维数组中使用 NSPredicate

c++ - C++ 中的链表析构函数 : should I delete?

c - 当代码中没有未初始化的全局或静态变量时,为什么 bss 段包含初始 4 个字节

c++ - 我的解决方案有什么问题?

C#直接赋值给对象引用