licoded / self-study-drafts

buffer for records
0 stars 0 forks source link

Amazing CPP: 重载赋值操作时,返回值是否使用引用的区别 #148

Open licoded opened 1 year ago

licoded commented 1 year ago

Point1: 两种形式不能同时写,是冲突的

Point2: 测试 &(a1=a2);,返回值不加引用会报错

但为什么中间变量不能去取地址???

6f50585b8ddf24b6c802e66124e1682c

Point3: 返回值不加引用就,多了一次拷贝

#include <iostream>

class A{
public:
    int a;

    A() { std::cout << "empty ctor" << std::endl; }
    A(int a):a(a){ std::cout << "A(int a) ctor" << std::endl; }
    A(A &A_):a(A_.a){ std::cout << "A(A &A_) ctor" << std::endl; }

    // A& operator=(const A& other){ // correspond to results1
    //     a = other.a;
    //     std::cout << "A& operator=(const A& other)" << std::endl;
    //     return *this;
    // }

    A operator=(const A& other){ // correspond to results2
        a = other.a;
        std::cout << "A operator=(const A& other)" << std::endl;
        return *this;
    }
};

int main()
{
    A a1(1), a2(2);
    std::cout
        << "===="
        << std::endl;

    a1 = a2;
    return 0;
}

results1:

A(int a) ctor
A(int a) ctor
A(int a) ctor
====
A operator=(const A& other)
A(A &A_) ctor

先赋值;赋值里面返回时,调了拷贝构造

results2:

A(int a) ctor
A(int a) ctor
A(int a) ctor
====
A& operator=(const A& other)