我正在阅读优秀的copy-and-swap idiom问答。但有一件事我不明白:在自我赋值的情况下,它是如何工作的?示例中提到的对象other不会释放分配给mArray的内存吗?那么,被自赋值的对象不会有一个无效的指针吗?
发布于 2011-04-26 16:15:07
,但是有一件事我不明白,在自赋值的情况下,它是如何工作的?
让我们看一下这个简单的案例:
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交换。当other超出作用域时,它会释放mArray (不出所料),但这是它自己的唯一副本,因为我们在执行复制操作时创建了一个深度副本。
,那么被自赋值的对象不会有一个无效的指针吗?
不是的。
https://stackoverflow.com/questions/5787495
复制相似问题