Detailed explanation of the return value type of the assignment operator function

In the study of the C ++ assignment operator function, the problem of the return value type has been very puzzling. Today, I thoroughly summarize the results of each different return value type:

1. When the return value is empty:

<span style="font-size:14px;">void hasptr::operator=(const hasptr& s)</span>


At this time, if there is only one '=' (a = b) operation, it will be ok, but if there is a chain operation of '=' (a = b = c), the compiler will report an error

We see: a = b = c;

The program will run b = c first;

Because the return value of the function is viod, so b = c this operation will return a NULL

Then this is a = (b = c), that is, a = NULL. This kind of operation does not exist. Even if it exists, it does not meet our original intention of this operation.


2. When the return value is the class itself:

<span style="font-size:14px;">hasptr hasptr::operator=(const hasptr& s)</span>


Support '=' chain operation

If the return value is the class itself, then the running process of this function is:

                      1. Enter the function and run the operation inside the function

                      2. After the operation inside the function is finished, call the copy constructor of the class to copy the object to a new object

                      3. Return to the newly created object


The key here is that every time the assignment operator function is run, the copy constructor is called, which not only wastes time.

If there is no copy constructor in the class, sometimes errors will occur.


3. When the return value is a reference

<span style="font-size:14px;">hasptr &hasptr::operator=(const hasptr& s)</span>


This method is the best, which supports chain operation, and also reduces the operation time to a minimum



Complete code:

<span style="font-size:14px;">hasptr &hasptr::operator=(const hasptr& s)
{
    i = s.i;
    string *x = new string(*s.ps);
    delete ps;
    ps = x;
    return *this;
}</span>


Published 190 original articles · 19 praises · 200,000+ views

Guess you like

Origin blog.csdn.net/zengchenacmer/article/details/38351385