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

I am reading a wonderful question and answers about the "copy and swap" error . But one thing I don't get: how does it work in the case of homing? Won't the other object mentioned in the example free up the memory allocated for mArray ? So will not an object that is self-tuning have an invalid pointer?

+4
source share
1 answer

But I do not understand how this works in the case of self-appointment?

Let's look at a 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; } 

Usually 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; } 

Would the object mentioned in this example free up the memory allocated for mArray?

Copy makes a deep copy of mArray.
Then we exchange it. When the other goes out of scope, it frees up the mArray (as expected), but this is its own unique copy, because we made a deep copy while performing the copy operation.

So, won't the object that is being assigned itself have an invalid pointer?

No.

+6
source

All Articles