复制和交换成语在自我转让过程中如何工作? [英] How does the copy-and-swap idiom work during self-assignment?
问题描述
我正在阅读优秀的复制与互换成语问题和答案。但有一件事我没有得到:在自我转让的情况下如何工作?在示例中提到的对象其他
不会释放分配给 mArray
的内存?那么自我分配的对象是不是最终会有一个无效的指针?
但是有一件事我没有得到如何在自我分配的情况下工作?
让我们来看一下简单的例子:
class Container
{
int * mArray;
};
//复制和交换
容器& operator =(Container const& rhs)
{
容器other(rhs); //你制作一个rhs的副本。
//这意味着你已经完成了一个深刻的副本,一个是$ r
$ b other.swap(* this); //这将交换mArray指针。
//所以如果rhs和*这是相同的对象它
//没关系,因为其他和*这是
//绝对不是同一个对象。
return * this;
}
通常你实现上述:
容器& operator =(Container other)
// ^^^^^^^^注意这里缺少`const&`
//这意味着它是一个通过值参数的值。
//当参数传递时,该副本是隐式的。
{
other.swap(* this);
return * this;
}
不会在示例释放分配给mArray的内存?
该副本制作了一个深度拷贝的mArray。
然后我们用this.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屋!