繁体   English   中英

在自我分配期间,复制和交换习语是如何工作的?

[英]How does the copy-and-swap idiom work during self-assignment?

我正在阅读优秀的复制和交换成语问题和答案。 但有一件事我没有得到:如果自我分配,它如何运作? 示例中提到的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;
}

示例中提到的其他对象是否会释放分配给mArray的内存?

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

因此,自我分配的对象最终是否会出现无效指针?

没有。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM