C++之令operator=返回一个reference to *this(10)---《Effective C++》

条款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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值