effective c++条款10

令赋值操作符返回一个reference to *this

如果赋值操作符不返回引用,那么它只能返回一个临时对象,用一个变量接收这个对象时还需要调用复制构造函数

代码:

#include <windows.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class E04
{
    friend ostream& operator<<(ostream out,E04& e04)
    {
        out<<e04.m_text;
    }
public:
    E04():m_text("Hello,world!")
    {
        cout<<"E04对象初始化"<<endl;
    }
    E04(string s):m_text(s){}
    E04(const char* s):m_text(s){}
    E04(const E04& other):m_text(other.m_text)
    {
        cout<<"运行拷贝构造函数"<<endl;
    }
    E04 operator=(const E04& other)
    {
        if(this==&other)
            return *this;
        this->m_text=other.m_text;
        return *this;
    }
    ~E04(){}
private:
    string m_text;
};
int main()
{
    E04 a("a");
    E04 b("b");
    E04 c("c");
    a=b=c;
    system("pause");
    return 0;
}

分析:a=b=c应该分解为b=c,a=b,所以如果不是引用,必须要调用两次复制构造函数
这里写图片描述
而如果返回的时候加上引用,返回的就是this本身,所以不需要调用copy构造函数

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值