assignment operator overloading in c++

前端 未结 6 1928
醉梦人生
醉梦人生 2021-02-01 15:07

I have used the following code for assignment operator overloading:

SimpleCircle SimpleCircle::operator=(const SimpleCircle & rhs)
{
     if(this == &rhs         


        
6条回答
  •  不思量自难忘°
    2021-02-01 15:41

    The second is pretty standard. You often prefer to return a reference from an assignment operator so that statements like a = b = c; resolve as expected. I can't think of any cases where I would want to return a copy from assignment.

    One thing to note is that if you aren't needing a deep copy it's sometimes considered best to use the implicit copy constructor and assignment operator generated by the compiler than roll your own. Really up to you though ...

    Edit:

    Here's some basic calls:

    SimpleCircle x; // default constructor
    SimpleCircle y(x); // copy constructor
    x = y; // assignment operator
    

    Now say we had the first version of your assignment operator:

    SimpleCircle SimpleCircle::operator=(const SimpleCircle & rhs)
    {
         if(this == &rhs)
            return *this; // calls copy constructor SimpleCircle(*this)
         itsRadius = rhs.getRadius(); // copy member
         return *this; // calls copy constructor
    }
    

    It calls the copy constructor and passes a reference to this in order to construct the copy to be returned. Now in the second example we avoid the copy by just returning a reference to this

    SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
    {
        if(this == &rhs)
           return *this; // return reference to this (no copy)
        itsRadius = rhs.getRadius(); // copy member
        return *this; // return reference to this (no copy)
    }
    

提交回复
热议问题