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; };
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.
source share