In some cases, we might end up with some code that assigns an object to itself. Therefore, when writing an ``++operator=++``, we must ensure that this use case works correctly, which may require special care. One technique to achieve this is to explicitly check at the start of ``++operator=++`` if we are assigning to ourselves, and in that case, just do nothing.


It is usually a bad idea to perform this check for optimization purposes only, because it optimizes for a very rare case while adding an extra check for the more common case. But when it is necessary for correctness, it should be added.


This rule raises an issue when an ``++operator=++`` does not check for assignment to self before proceeding with the assignment.


== Noncompliant Code Example

----
class MyClass
{
  private:
  int someVal;
  char* pData;

  MyClass& operator=(const MyClass& rhs)
  {
    this->someVal = rhs.someVal;              // useless operation in self-assignment, but very fast
    delete [] pData;                          // data is lost in self-assignment
    pData = new char[strlen(rhs.pData) +1];   // null pointer dereference or use after free in self-assignment
    strcpy(pData, rhs.pData);

    return (*this);
  }
};
----


== Compliant Solution

----
class MyClass
{
  private:
  int someVal;
  char* pData;

  MyClass& operator=(const MyClass& rhs)
  {
    if (this != &rhs)
    {
      this->someVal = rhs.someVal;
      delete [] pData;
      pData = new char[strlen(rhs.pData) +1];
      strcpy(pData, rhs.pData);
    }
    return (*this);
  }
};
----
Or much better:

----
class MyClass
{
  private:
  int someVal;
  std::string data; // No need for manual operator=
};
----

