tracing calls to copy constructor

264 views Asked by At
#include <iostream>
using namespace std;

class Student
{
public :
    Student() { };
    Student(const Student& s) { cout << "COPY CONSTRUCTOR CALLED\n";}
};

Student f(Student u)
{
    Student v(u);
    Student w = v;
    return w;
}

main()
{
    Student x;
    Student y = f(f(x));
}

According to me there should be 8 calls as each function call calls the copy constructor 4 times.

1) copying x to parameter u
2) copying u to v
3) copying v to w
4 ) returning w

Please help me. I am having lots of difficulty in understanding these concepts.

2

There are 2 answers

1
Nivetha On BEST ANSWER

Each function call will call the copy constructor 3 times. This is due to Return Value Optimization (RVO). The first call will call the copy constructor 3 times and the second call will call the constructor 2 times only because the return value of the first is being passed on to the second.

The first call the copy constructor is called at:

1) Copying x to u
2) Copying u to v
3) Copying v to w

The second time the copy constructor is called at:

1) Copying u to v
2) Copying v to w

At other places, optimization is done by the compiler.

5
R Sahu On

Some of the places where you'd expect copy constructors to get called don't really get called due to return value optimization (RVO).

If I compile your code using:

g++ -Wall -std=c++11

I get the following output:

COPY CONSTRUCTOR CALLED
COPY CONSTRUCTOR CALLED
COPY CONSTRUCTOR CALLED
COPY CONSTRUCTOR CALLED
COPY CONSTRUCTOR CALLED

If I compile your code using:

g++ -Wall -std=c++11  -fno-elide-constructors

I get the following output.

COPY CONSTRUCTOR CALLED
COPY CONSTRUCTOR CALLED
COPY CONSTRUCTOR CALLED
COPY CONSTRUCTOR CALLED
COPY CONSTRUCTOR CALLED
COPY CONSTRUCTOR CALLED
COPY CONSTRUCTOR CALLED
COPY CONSTRUCTOR CALLED
COPY CONSTRUCTOR CALLED