5

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?

Community
  • 1
  • 1
Asha
  • 11,002
  • 6
  • 44
  • 66

1 Answers1

7

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.

Martin York
  • 257,169
  • 86
  • 333
  • 562
  • Oops.. I missed the deep copy in the copy ctor..thanks for the explanation. – Asha Apr 26 '11 at 08:22
  • 1
    Old post but i m stuck at the same doubt.. isn't it too much overhead as oppossed to `if (this == &other) return *this;` in case of self assigment when using copy-swap idiom? – Hummingbird Nov 22 '16 at 06:41
  • 3
    @Hummingbird: There is more overhead in the case where there is self assignment. **BUT** self assignment is exceedingly rare (vanishingly small in real code). If you look at the other way around. If you are optimizing the code for self assignment then you are pesimizing the code for normal operation. Now the normal operation is so much more common that it can actually make a measurable difference (and people have done that timing). I am willing to pay the extra cost in situations that happen exceedingly rarely for the optimal code in situations that happen quite frequently. – Martin York Nov 22 '16 at 07:08