条款10:令operator=返回一个reference to *this,即返回指向本类的引用。
以前老有一个疑问,operator=为什么几乎所有的C++程序中的返回值都设置为指向本类的引用呢?曾经以为是因为连续赋值的问题,设置为引用可以实现连续赋值,不设置的话可能无法实现???那么答案到底是什么呢?
现在来参看如下代码:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
class Hello{
public:
Hello(){
}
Hello(int x, int y) :x(x), y(y){
}
Hello(Hello& h){
this->x = h.x;
this->y = h.y;
}
Hello& operator=(const Hello& h){
this->x = h.x;
this->y = h.y;
return *this;
}
void show(){
cout << x << " " << y << endl;
}
~Hello(){
}
private:
int x;
int y;
};
int main(){
Hello h1(1, 10), h2, h3, h4;
h4 = h3 = h2 = h1;
h4.show();
h3.show();
h2.show();
return 0;
}
运行结果为:
如果我们令代码变为这样呢?
...
Hello operator=(const Hello& h){
this->x = h.x;
this->y = h.y;
return *this;
}
...
运行结果为:
可以发现,我们上述的假设错误,不管返回值设置为类对象或者类引用,程序都可以正常执行。**
那么究竟返回值为Hello&和Hello有什么差距呢?其实是效率的问题,如果我们使用返回值为Hello&的话,那么在赋值操作时候直接就使用引用,不用创建临时对象,可以一部分提高程序的效率,
**因此,建议大家将operator=的返回值设置为reference to *this。