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构造函数

猜你喜欢

转载自blog.csdn.net/baidu_25539425/article/details/79927348