Assignment operator in C++

From Seo Wiki - Search Engine Optimization and Programming Languages

Jump to: navigation, search

The assignment operator in C++ programming language is '='. Like most other operators in C++, it can be overloaded.

The copy assignment operator is a special case of assignment operator used to assign objects of the same class to each other. It is one of the special member functions, and is generated automatically by the compiler if not explicitly declared by the programmer. The compiler-generated code performs a memberwise shallow copy.

The copy assignment operator differs from the copy constructor in that it must clean up the data members of the assignment's target (and correctly handle self-assignment) whereas the copy constructor assigns values to uninitialized data members.[1] For example:

My_Array first;           // initialization by default constructor
My_Array second(first);   // initialization by copy constructor
My_Array third = first;   // Also initialization by copy constructor
second = third;           // assignment by 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[other.count];
            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;
        }
        // by convention, 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 [2]:

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);
 
        // by convention, always return *this
        return *this;
 
        // other is destroyed, releasing the memory
    }

The reason why operator = returns My_Array& instead of void is simple. It allows for concatenation of assignments like this:

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

See also

References

  1. Stroustrup, Bjarne (2000). The C++ Programming Language (3 ed.). Addison-Wesley. p. 244. ISBN 978-0201700732. 
  2. Sutter, H.; Alexandrescu, A. (October 2004), C++ Coding Standards, Addison-Wesley, ISBN 0-321-11358-6 
ru:Операция присваивания в С++

zh:C++設定運算子

Personal tools

Served in 0.185 secs.