Jason
Jason

Reputation: 1307

Why is the copy constructor called in this code after the assignment operator?

If I modify the assignment opreator so that it returns an object A instead of a reference to an object A then something funny happens.

Whenever the assignment operator is called, the copy constructor is called right afterwards. Why is this?

#include <iostream>
using namespace std;

class A {
private:
    static int id;
    int token;
public:
    A() { token = id++; cout << token << " ctor called\n";}
    A(const A& a) {token = id++; cout << token << " copy ctor called\n"; }
    A /*&*/operator=(const A &rhs) { cout << token << " assignment operator called\n"; return *this; }
};

int A::id = 0;

A test() {
    return A();
}

int main() {
    A a;
    cout << "STARTING\n";
    A b = a;
    cout << "TEST\n";
    b = a;
    cout << "START c";
    A *c = new A(a);
    cout << "END\n";
    b = a;
    cout << "ALMOST ENDING\n";
    A d(a);
    cout << "FINAL\n";
    A e = A();
    cout << "test()";
    test();

    delete c;
    return 0;
}

The output is as follows:

0 ctor called
STARTING
1 copy ctor called
TEST
1 assignment operator called
2 copy ctor called
START c3 copy ctor called
END
1 assignment operator called
4 copy ctor called
ALMOST ENDING
5 copy ctor called
FINAL
6 ctor called
test()7 ctor called

Upvotes: 0

Views: 655

Answers (1)

Gabrielle de Grimouard
Gabrielle de Grimouard

Reputation: 2005

Because if you don't return a reference of the object it makes a copy. As @M.M said about the final test() call, the copy does not appears because of the copy elision What are copy elision and return value optimization?

Upvotes: 5

Related Questions