Effective C++手册Item 10: 让 assignment operators(赋值运算符)返回一个 reference to \*this(引向 \*this 的引用)

Item 10: 让 assignment operators(赋值运算符)返回一个 reference to \*this(引向 \*this 的引用)

作者:Scott Meyers

译者:fatalerror99 (iTePub's Nirvana)

发布:http://blog.csdn.net/fatalerror99/

关于 assignments(赋值)的一件有意思的事情是你可以把它们穿成一串。

int x, y, z;
x = y = z = 15; // chain of assignments

另一件有意思的事情是 assignment(赋值)是 right-associative(右结合)的,所以,上面的赋值串可以解析成这样:

x = (y = (z = 15));

这里,15 赋给 z,然后将这个 assignment(赋值)的结果(最新的 z)赋给 y,然后将这个 assignment(赋值)的结果(最新的 y)赋给 x。

这里的实现方法是让 assignment(赋值)返回一个 reference to its left-hand argument(引向它的左侧参数的引用),而且这就是当你为你的 classes(类)实现 assignment operators(赋值运算符)时应该遵守的惯例:

class Widget {
public:
  ...
Widget& operator=(const Widget& rhs)   // return type is a reference to
{                                      // the current class
  ...
  return *this;                        // return the left-hand object
  }
  ...
};

这个惯例适用于所有的 assignment operators(赋值运算符),而不仅仅是上面那样的标准形式。因此:

class Widget {
public:
  ...
  Widget& operator+=(const Widget& rhs   // the convention applies to
  {                                      // +=, -=, *=, etc.
   ...
   return *this;
  }
   Widget& operator=(int rhs)            // it applies even if the
   {                                     // operator's parameter type
      ...                                // is unconventional
      return *this;
   }
   ...
};

这仅仅是一个惯例,代码并不会按照这个意愿编译。然而,这个惯例被所有的 built-in types(内建类型)和标准库中(或者即将进入标准库——参见 Item 54)的 types(类型)(例如,string,vector,complex,tr1::shared_ptr 等)所遵守。除非你有好的做不同事情理由,否则,不要破坏它。

Things to Remember

  • 让 assignment operators(赋值运算符)返回一个 reference to *this(引向 *this 的引用)。