简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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