c++ - 为什么赋值运算符重载会创建一个对象的拷贝?

标签 c++ class operator-overloading copy-constructor

在下面给出的代码中,我在所有的类构造函数、析构函数和重载赋值运算符中编写了cout语句。

#include <iostream>
using namespace std;

class person {
    string name;
    int age ;
    int id ;
    static int num;
public :
    person (string name , int age) : name(name) , age(age) {
        id = num++;
        cout << "creating person : " << id << "(" << name <<")"<< endl;
    }
    person (const person &other) : name(other.name) , age(other.age) {
            id = num++;
            cout << "CREATING PERSON  : " << id << "(" << name <<")" << " from : " << other.id << endl;
    }
    ~person () {
        cout << "killing person : " << id << "(" << name <<")" << endl;
    }
    const person operator= (const person &other) {
        name = other.name ;
        age = other.age;
        //id = num++;
        cout << "copying in : " << id << "(" << name <<")" << " from : " << other.id << endl;
        return *this;
    }
    void print () {
        cout << "name : " << name << ", age : " << age << ", id : " << id << endl;
    }

int person::num = 1;

int main() {
    person per1 ("p1" , 20);
    person per2 ("p2" , 30);
    person per3 ("p3" , 40);
    cout << "see the strange object creation here: " << endl << endl;
    per3 = per2 = per1;
    return 0;
}

给定代码的输出结果是:

creating person : 1(p1)
creating person : 2(p2)
creating person : 3(p3)
see the strange object creation here:
copying in : 2(p1) from : 1
*CREATING PERSON  : 4(p1) from : 2*
copying in : 3(p1) from : 4
*CREATING PERSON  : 5(p1) from : 3*
killing person : 5(p1)
killing person : 4(p1)
killing person : 3(p1)
killing person : 2(p1)
killing person : 1(p1)

我的问题是,是什么导致使用复制构造函数创建两个对象(4 和 5)?分配中使用的对象已经存在。有没有办法在不创建虚拟对象的情况下重载赋值运算符?这个方法看起来不是很优化。

最佳答案

那是因为你的 operator=() 看起来像这样:

const person operator= (const person &other)

按值返回。 const 在此上下文中没有真正意义。

您实际上想做的是通过常量引用返回:

const person& operator= (const person &other)

那个 & 会让一切变得不同。

关于c++ - 为什么赋值运算符重载会创建一个对象的拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61947356/

相关文章:

c++ - 为什么这些完全相似的代码不起作用?

c++ - 如何让 cout 缓冲区在 ubuntu 上刷新

c++ - 在单独的函数中创建一个动态数组并通过调用函数对其进行操作

C# 类问题

C++:在方法内部可以从类创建未初始化的对象吗?

python - 是什么让用户定义的类不可散列?

c++ - 重载内部没有数组的 [] 运算符

c++ - 3D vector 的高效除法运算符

c++ - 如果已经设置,则在 CMake 中更改标志值

c++ - 一元 + on 指针