Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) operator=

 

operator= is an operator, that is called the assign operator and assignment operator.

 

struct MyClass
{
  MyClass& operator=(const MyClass& rhs)
  {
    //Copy the class members
    return *this;
  }
};

 

In class design, have assignment operators return a reference to *this [1].

 

In class design, also handle assignment to self [2]. To handle assignment to self there are two techniques: 'identity test' or 'copy and swap'.

 

 

 

 

 

Handle assignment to self: Identity test

 

struct MyClass
{
  MyClass& operator=(const MyClass& rhs)
  {
    //'Identity test'
    if (this == &rhs) return *this;

    //Copy
    //...

    //Return *this
    return *this;
  }
};

 

 

 

 

 

Handle assignment to self: Copy and swap

 

struct MyClass
{
  MyClass& operator=(MyClass tempCopy) //'Copy' (by passing by value)
  {
    //'Swap'
    Swap(tempCopy); //Swaps the data of temp with *this

    return *this;
  }

  void Swap(MyClass& m)
  {
    //Swap data of m with this
    std::swap(mX, m.mX);
    //Other data...
  }

  int mX; //Just to have a member variable
};

 

 

 

 

 

References

 

  1. Scott Meyers. Effective C++ (3rd edition).ISBN: 0-321-33487-6. Item 10: Have assignment operators return a reference to *this.
  2. Scott Meyers. Effective C++ (3rd edition).ISBN: 0-321-33487-6. Item 11: Handle assignment to self in operator=.

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict