Assignment Operator (C++) - Overloading Copy Assignment Operator

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:

  1. Acquire new resources
  2. Release old resources
  3. Assign the new resources' handles to the object
class My_Array { int * array; int count; public: My_Array & operator= (const My_Array & other) { if (this != &other) // protect against invalid self-assignment { // 1: allocate new memory and copy the elements int * new_array = new int; std::copy(other.array, other.array + other.count, new_array); // 2: deallocate old memory delete array; // 3: assign the new memory to the object array = new_array; count = other.count; } // to support chained assignment operators (a=b=c), always return *this return *this; } // ... };

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:

array_1 = array_2 = array_3; // array_3 is assigned to array_2 // and then array_2 is assigned to array_1

The operator returns a non-const My_Array& to allow the following statement:

( array_1 = array_2 ) = array_3;

Note that this is allowed for basic types like int.

Read more about this topic:  Assignment Operator (C++)

Famous quotes containing the word copy:

    Quotations—always inexact. I don’t trust people who cannot even copy out.
    Jean Rostand (1894–1977)