简体   繁体   中英

Why does assignment operator overloading create a copy of an object?

In the below given code, I have written cout statements in all the class constructors, destructor and overloaded assignment operator.

#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;
}

The output of the given code comes out to be:

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)

My question is, what caused two objects (4 and 5) to be created with the copy constructor? The objects used in assignment were already existing. Is there a way to overload the assignment operator without creating dummy objects? This method does not seem very optimized.

That's because your operator=() looks like this:

const person operator= (const person &other)

That returns by value. const doesn't really make sense in this context.

What you actually mean to do is return by constant reference instead:

const person& operator= (const person &other)

That one & will make all the difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM