Fork me on GitHub

读书笔记 effective c++ Item 10 让赋值运算符返回指向*this的引用

一个关于赋值的有趣的事情是你可以将它们链在一起:

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

同样有趣的是赋值采用右结合律,所以上面的赋值链被解析成下面这个样子:

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

在这里,15被赋值给z,然后赋值的结果(更新的z)被赋值给y,再然后赋值的结果(更新的Y)被赋值给x。

实现这个赋值链的方法是使赋值返回指向左边参数的引用,这也是你在为你的类实现赋值运算符的时候应该遵守的约定:

 1 class Widget {
 2 
 3 public:
 4 
 5 ...
 6 
 7 Widget& operator=(const Widget& rhs) // return type is a reference to
 8 
 9 { // the current class
10 
11 ...
12 
13 return *this; // return the left-hand object
14 
15 }
16 
17 ...
18 
19 };

这个约定除了适用于上面的标准形式之外,也适用于所有的赋值运算符,因此:

 1 class Widget {
 2 
 3 public:
 4 
 5 ...
 6 
 7 Widget& operator+=(const Widget& rhs) // the convention applies to
 8 
 9 { // +=, -=, *=, etc.
10 
11 ...
12 
13 return *this;
14 
15 }
16 
17 Widget& operator=(int rhs) // it applies even if the
18 
19 { // operator’s parameter type
20 
21 ... // is unconventional
22 
23 return *this;
24 
25 }
26 
27 ...
28 
29 };

这仅仅是一个约定,没有遵循这个约定的代码也能通过编译。然而,所有的内建类型和标准库(像string,vector,complex,tr1::shared_ptr等等)中的所有类型(或即将提供的类型,见Item54)都遵守这个约定。因此除非你有更好的理由,否则请遵守这个约定。

posted @ 2017-02-15 23:42  HarlanC  阅读(635)  评论(0编辑  收藏  举报