Overloading Copy Assignment Operator
When deep copies of objects have to be made, exception safety should be taken into consideration. One way to achieve this when resource deallocation never fails is:
- Acquire new resources
- Release old resources
- Assign the new resources' handles to the object
However, if a no-fail (no-throw) swap function is available for all the member subobjects and the class provides a copy constructor and destructor (which it should do according to the rule of three), the most straightforward way to implement copy assignment is as follows :
public: void swap(My_Array & other) // the swap member function (should never fail!) { // swap all the members (and base subobject, if applicable) with other std::swap(array, other.array); std::swap(count, other.count); } My_Array & operator = (My_Array other) // note: argument passed by value! { // swap this with other swap(other); // to support chained assignment operators (a=b=c), always return *this return *this; // other is destroyed, releasing the memory }The reason why operator = returns My_Array&
instead of void
is to allow chained assignments like the following:
The operator returns a non-const My_Array&
to allow the following statement:
Note that this is allowed for basic types like int
.
Read more about this topic: Assignment Operator (C++)
Famous quotes containing the word copy:
“The men are magnificentthe young men tall, well formed, and admirably dressed; the old men positively beautiful, with their fresh complexions, white hair, and admirable neatness. Nothing struck me more than this, and we might copy it to advantage here. As an Englishman grows older he becomes more and more careful in his dress.”
—M. E. W. Sherwood (18261903)