简体   繁体   中英

Why is the copy constructor being called here?

#include <iostream>
using namespace std;
class A
{
    int x;
public:

    A(int a)
    {   
        x = a;
        cout << "CTOR CALLED";
    }
    A(A &t)
    {
        cout << "COPY CTOR CALLED";
    }
    void display()
    {
        cout << "Random stuff";
    }
    A operator = (A &d)
    {   
        d.x = x;
        cout << "Assignment operator called";
        return *this;
    }
};

int main()
{
    A a(3), b(4);
    a = b;
    return 0;
}

The output of this code is :

CTOR CALLED
CTOR CALLED
Assignment operator called
COPY CTOR CALLED

When I used the watch in visual studio it showed that the value of x in a had been changed even before the overloaded assignment operator was called.

So why is the copy constructor even being called here?

Because you return by value from the assignment operator. It should return a reference :

A& operator = (A &d) { ... }

As @SomeProgrammerDude already said, it's because you return by value, not by reference like you usually do with an assignment operator. I would like to add that your assignment operator is currently the wrong way around:

A operator = (A &d)
{   
    d.x = x;
    cout << "Assignment operator called";
    return *this;
}

Usually you pass d by const reference because we want to alter the members of this . You are changing the members of d . Which would functionally turn your a = b; into b = a; since a = b; is actually changing members of b now !

Making d a const& prevents these mistakes.

You should change it to:

A& operator = (A const &d)
{   
    x = d.x;
    cout << "Assignment operator called";
    return *this;
}

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