C ++ Overload Assignment Operator

I have a class called Location, and I need to add CArray to its member variables. This change made it necessary to overload the assignment operator.

Is there a way to copy all the variables of this type that were copied before I made the changes and just add extra code to copy the CArray without copying each individual member variable individually?

Location& Location::operator=(const Location &rhs) 
{
    // Only do assignment if RHS is a different object from this.
    if (this != &rhs) 
    {
        //Copy CArray
        m_LocationsToSkip.Copy(rhs.m_LocationsToSkip);

        //Copy rest of member variables
        //I'd prefer not to do the following
        var1 = rhs.var1;
        var2 = rhs.var2;
        //etc
    }

    return *this;
}
+5
source share
4 answers

, . , operator= , . MFC - std::vector, std::string .. MFC . CString, , CArray std::vector.

+4

. , , , Members , , . :

class Location
{
   struct Members
   {
      int var1, var2;
   };

   Members m;
   CArray m_LocationsToSkip;

public:
   Location& operator=(Location const& rhs);
};

Location& Location::operator=(const Location &rhs) 
{
    // Only do assignment if RHS is a different object from this.
    if (this != &rhs) 
    {
        //Copy CArray
        m_LocationsToSkip.Copy(rhs.m_LocationsToSkip);

        //Copy rest of member variables
        m = rhs.m; //will use Members automatically generated operator=
                   //which should do the correct thing because you only put
                   //normally copyable members in m
    }

    return *this;
}

: https://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-utility/1609496#1609496

+2

, . - script .

0

This is usually done using the so-called "copy and swap idioms." You implement a copy constructor and a method swap()that exchanges the values ​​of elements and, most importantly, points to external data. In this case, your assignment operator looks like this:

C& C::operator=( const C& c ) {
    C tmp( c );
    this->swap( tmp );
    return *this;
}

You don’t even need to protect yourself.

0
source

All Articles