C++ Idioms           

赋值运算符(assignment operator)中自赋值(self-assignment)的处理

T::operator= 需要处理左操作数 (LHS) 和右操作数 (RHS)指向同一个对象的情况。

T& operator= (const T& that)
{
    if (this == &that)
        return *this;

    // handle assignment here

    return *this;
}

注意事项

比如 T 所有的成员(mem1, mem2, … memeN)都提供了 swap() 函数,那么 operator= 重载就可以这样写:  

T& operator= (T that)
{
   // that is constructed by the copy constructor

   mem1.swap (that.mem1);
   mem2.swap (that.mem2);

   ...

   memN.swap (that.memN);
 
   // now what were originally this->mem1, this->mem2, etc. get
   // destroyed when that gets destroyed, and that.mem1, etc. are
   // retained in *this 
   return *this;
} # CRTP (Curiously Recurring Template Pattern 用 static polyphormism 模拟 runtime polyphormism, 没有 runtime polyphormism 的开销

template <class Derived>
  struct base
  {
      void interface()
      {
          // ...
          static_cast<Derived*>(this)->implementation();
          // ...
      }

      static void static_interface()
      {
          // ...
          Derived::static_implementation();
          // ...
      }

      // The default implementation may be (if exists) or should be (otherwise) 
      // overridden by inheriting in derived classes (see below)
      void implementation();
      static void static_implementation();
  };

  // The Curiously Recurring Template Pattern (CRTP)
  struct derived_1 : base<derived_1>
  {
      // This class uses base variant of implementation
      //void implementation();

      // ... and overrides static_implementation
      static void static_implementation();
  };

  struct derived_2 : base<derived_2>
  {
      // This class overrides implementation
      void implementation();

      // ... and uses base variant of static_implementation
      //static void static_implementation();
  };