user5028722
user5028722

Reputation:

Why is the copy constructor called twice?

In the following code, the copy constructor is being called twice, why?

#include <iostream>
using namespace std;
class A {
    int X;
public:
    A() {
        cout << "Simple Constructor" << endl;
    }
    A(int b) :X(b) {
        cout << "Constructor " << X << endl;
    }
    A(const A& obj) :X(obj.X) {
        cout << "Copy Constructor " << endl;
    }
    ~A() {
        cout << "Destructor " << X << endl;
    }
};
A fun(A obj) {
    cout << "Fun" << endl;
    return obj;
}
int main() {
    A obj(10);
    obj = fun(obj); // here is confusion
    cout << "End" << endl;
    return 0;
}

Output:

Constructor 10
Copy Constructor
Fun
Copy Constructor
Destructor 10
Destructor 10
End
Destructor 10

I'm thinking maybe the second copy constructor is being called due to temporary object.

Upvotes: 3

Views: 1058

Answers (1)

Estiny
Estiny

Reputation: 888

The first call of copy constructor is performed when you call fun(obj). You pass obj by value, so it is copied and the copy is used inside of the function. Next copy is performed when you return obj in fun. It is also returned by value, so it is copied again.

I don't know what is your intent. If you want to modify the object in function, it would be better to pass it by reference and make function void:

void fun(A& obj) {
    cout << "Fun" << endl;
}

and just call

fun(obj);

This way you prevent both calls to copy constructor.

Edit:

If you wonder why Return Value Optimization is not performed, you should know that it is optional behavior, that is allowed for the compiler by the standard. First you should make sure that your compiler is allowed to optimise the code (eg. you don't use Debug Build) and then that it actually supports RVO. Finaly you should think if the optimization really makes sense in this case. Your object has only one int inside, so it has a size of the base type. One thing to remember about optimization is that it CAN be performed but compiler is the one that decides, whether to perform it or not.

Upvotes: 4

Related Questions