读书笔记_Effective_C++_条款十:令operator=返回一个reference to *this
2013-03-20 23:15
176 查看
这个条款很简单的说,先解释一下为什么赋值后还要有返回值,这是因为我们可以这样用连等:
注意等号是右结合的,所以上述运算实际上等同于:
如果没有返回值,上述代码就不能通过编译。
至于为什么返回的是一个引用,这并不是编译器强制的,但有三个原因让你觉得这样做是明智的:
(1) 返回引用可以节省资源,不必要为返回值调用构造函数了;
(2) 形如(x = y) = 3这样的连等,编译器也能接受了,因为这样的写法要求赋值运算符返回的是可以修改的左值;
(3) STL和boost库中的标准代码都是这样写的,为了与它们相兼容,还是放弃你的标新立异吧
类似地,+=、-=等与赋值相关的运算,最好也返回自身的引用。
一句话:令赋值操作符返回一个reference to *this。
int x, y, z; x = y = z;
注意等号是右结合的,所以上述运算实际上等同于:
x = (y = z);
如果没有返回值,上述代码就不能通过编译。
至于为什么返回的是一个引用,这并不是编译器强制的,但有三个原因让你觉得这样做是明智的:
(1) 返回引用可以节省资源,不必要为返回值调用构造函数了;
(2) 形如(x = y) = 3这样的连等,编译器也能接受了,因为这样的写法要求赋值运算符返回的是可以修改的左值;
(3) STL和boost库中的标准代码都是这样写的,为了与它们相兼容,还是放弃你的标新立异吧
类似地,+=、-=等与赋值相关的运算,最好也返回自身的引用。
一句话:令赋值操作符返回一个reference to *this。
相关文章推荐
- Effective C++——》条款10:令operator=返回一个reference to *this
- 读书笔记《Effective c++》 条款10 令operator= 返回一个reference to *this
- Effective C++ Item 10 令operator= 返回一个reference to *this
- 读书笔记《Effective C++》条款10:令operator=返回一个reference to *this
- effective c++ 令operator=返回一个reference to *this
- Effective C++ Item 10 令operator= 返回一个reference to *this
- 条款10-11:令operator=返回一个reference to *this
- 条款十 令 operator = 返回一个 reference to *this
- Effective C++ Item10-令operator = 返回一个reference to *this
- 条款10:令operator=返回一个reference to * this(Have assignment operators return a reference to *this)
- 条款10 令operator=返回一个reference to *this
- 条款10:令operator=返回一个reference to *this
- effective C++ 条款 10:operator= 返回一个reference to *this
- 《Effective C++ 》条款10:令operator=返回一个reference to *this
- 条款10:让operator=返回一个reference to *this
- 条款10:令operator= 返回一个reference to *this
- 【effective c++】条款10:令operator=返回一个reference to *this
- 条款10:令operator=返回一个reference to *this
- 条款10:令operator=返回一个reference to *this
- 条款10:令operator=返回一个reference to * this