Assignment operator (C++)

Assignment operator (C++)

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

The copy assignment operator, often just called the "assignment operator", is a special case of assignment operator where the source (right-hand side) and destination (left-hand side) are of the same class type. It is one of the special member functions, which means that a default version of it is generated automatically by the compiler if the programmer does not declare one. The default version performs a memberwise copy, where each member is copied by its own copy assignment operator (which may also be programmer-declared or compiler-generated).

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 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 chained assignments:

array_1 = (array_2 = array_3); // The assignment operator (=) has right-to-left associativity
                               // array_3 is assigned to array_2 
                               // and then array_2 is assigned to array_1

Note that this is allowed for basic types like int.

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 

Wikimedia Foundation. 2010.

Игры ⚽ Поможем сделать НИР

Look at other dictionaries:

  • Assignment operator in C++ — ––The assignment operator in C++ programming language is = . Like 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 …   Wikipedia

  • Assignment (computer science) — In computer programming, an assignment statement sets or re sets the value stored in the storage location(s) denoted by a variable name. In most imperative computer programming languages, assignment statements are one of the basic statements.… …   Wikipedia

  • Assignment Vienna — was a drama television series aired in the United States by ABC as an element in its 1972 73 wheel series The Men . Assignment Vienna told the story of Jake Webster (Robert Conrad), an American expatriate in Vienna who was the operator of Jake s… …   Wikipedia

  • Operator associativity — For the mathematical concept of associativity, see Associativity. In programming languages and mathematical notation, the associativity (or fixity) of an operator is a property that determines how operators of the same precedence are grouped in… …   Wikipedia

  • ?? Operator — The ?? operator, sometimes called the Coalescing Operator, is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, most notably C#.Conditional assignment?? is most frequently used to… …   Wikipedia

  • Relational operator — In computer science, a relational operator is a programming language construct or operator that tests or defines some kind of relation between two entities. These include numerical equality (e.g., 5 = 5) and inequalities (e.g.,… …   Wikipedia

  • Augmented assignment — (or compound assignment) is the name given to certain operators in certain programming languages (especially those derived from C). An augmented assignment is generally used to replace a statement where an operator takes a variable as one of its… …   Wikipedia

  • Common operator notation — This article is about the concept of operator precedence. For operator precedence parsing, see operator precedence parser. In programming languages, common operator notation is one way of notating mathematical expressions as a linear sequence of… …   Wikipedia

  • μ operator — In computability theory, the μ operator, minimization operator, or unbounded search operator searches for the least natural number with a given property. Contents 1 Definition 2 Properties 3 Examples …   Wikipedia

  • Μ operator — In computability theory, the μ operator, minimization operator, or unbounded search operator searches for the least natural number with a given property. Definition Suppose that R( y, x1 , . . ., xk ) is a fixed k+1 ary relation on the natural… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”