在自我分配期间,复制和交换习语是如何工作的? [英] How does the copy-and-swap idiom work during self-assignment?

查看:135
本文介绍了在自我分配期间,复制和交换习语是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读卓越的复制和交换惯用语问题和答案。但有一件事我没有得到:在自我分配的情况下它是如何工作的?在示例中提到的对象其他不会释放分配给 mArray 的内存吗?因此,自我分配的对象不会有无效的指针?

解决方案


<但是有一件事我没有得到它是如何工作的情况下自我分配?


让我们看看这个简单的例子:

  class Container 
{
int * mArray;
};

//复制和交换
容器& operator =(Container const& rhs)
{
容器其他(rhs); //你制作rhs的副本。
//这意味着你已经做了一个深入的mArray副本

other.swap(* this); //这将交换mArray指针。
//所以如果rhs和*这是相同的对象它
//不重要,因为其他和*这是
//绝对不是同一个对象。

return * this;
}

通常,您将上述操作实现为:

  operator =(Container other)
// ^^^^^^^注意这里缺少`const&`
//这意味着它是一个传递值的参数。
//拷贝是在传递参数时隐式作出的。
{
other.swap(* this);

return * this;
}




示例释放分配给mArray的内存?


该副本会生成一个mArray的深拷贝。

然后我们用这个mArray交换。当其他超出范围它释放mArray(如预期),但这是它自己的唯一副本,因为我们在执行复制操作时做了一个深层副本。


那么,自我分配的对象最终会有一个无效的指针呢?


/ p>

I am reading the excellent copy-and-swap idiom question and answers. But one thing I am not getting: How does it work in case of self-assignment? Wouldn't the object other mentioned in the example release the memory allocated to mArray? So wouldn't the object which is being self-assigned end up in having an invalid pointer?

解决方案

But one thing I am not getting how does it work in case of self assignment?

Lets look at the simple case:

class Container
{
    int*   mArray;
};

// Copy and swap
Container& operator=(Container const& rhs)
{
    Container   other(rhs);  // You make a copy of the rhs.
                             // This means you have done a deep copy of mArray

    other.swap(*this);       // This swaps the mArray pointer.
                             // So if rhs and *this are the same object it
                             // does not matter because other and *this are
                             // definitely not the same object.

    return *this;
}

Normally you implement the above as:

Container& operator=(Container other)
                       // ^^^^^^^^     Notice here the lack of `const &`
                       //              This means it is a pass by value parameter.
                       //              The copy was made implicitly as the parameter was passed. 
{
    other.swap(*this);

    return *this;
}

Wouldn't the object other mentioned in the example release the memory allocated to mArray?

The copy makes a deep copy of mArray.
We then swap with this.mArray. When other goes out of scope it releases mArray (as expected) but this is its own unique copy because we made a deep copy when the copy operation is performed.

So wouldn't the object which is being self assigned end up in having an invalid pointer?

No.

这篇关于在自我分配期间,复制和交换习语是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆