我正在阅读优秀的copy-and-swap idiom问题和答案。但有一件事我没有得到:如果自我分配,它如何运作?示例中提到的对象other
是否会释放分配给mArray
的内存?那么自我分配的对象最终是否会出现无效指针?
答案 0 :(得分:6)
但有一件事我没有得到它如何在自我分配的情况下工作?
让我们看一下这个简单的案例:
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;
}
通常你将上面的内容实现为:
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;
}
示例中提到的其他对象是否会释放分配给mArray的内存?
该副本制作了mArray的深层副本 然后我们用this.mArray交换。当其他超出范围时,它会释放mArray(如预期的那样),但这是它自己的唯一副本,因为我们在执行复制操作时进行了深层复制。
那么自我分配的对象最终是否会出现无效指针?
没有