我正在阅读优秀的复制并交换惯用语问题和答案。但是有一件事情我没有理解:在自我赋值的情况下,它是如何工作的?在示例中提到的other
对象不会释放分配给mArray
的内存吗?因此,被自我赋值的对象最终会拥有一个无效指针吗?
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;
}
if (this == &other) return *this;
相比,这是否会产生过多的开销? - Hummingbird