1
#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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270

2 Answers2

1

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.

Nivetha
  • 698
  • 5
  • 17
  • When I compiled using gcc compiler there were 7 calls. Also I don't understand why there would be know call when returning. – Rishabh Kumar Jun 07 '15 at 05:03
0

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
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Why there are 5 in the first one and 9 in the second. Could you please explain ? – Rishabh Kumar Jun 07 '15 at 05:04
  • @RishabhKumar, the explanation by Nivetha [in his answer](http://stackoverflow.com/a/30690214/434551) explains it. – R Sahu Jun 07 '15 at 05:09
  • -fno-elide-constructors specifies to the compiler not to create temporaries. Hence in the second case, there are 9 calls. In the first case, with optimization, there are only 5 calls as i explained in my answer. – Nivetha Jun 07 '15 at 05:09
  • Okay I understand your explations but can you also make it clear when could it possibly have 7 calls. – Rishabh Kumar Jun 07 '15 at 05:13
  • @RishabhKumar, No, I can't explain why you have 7 calls. It doesn't make sense to me. – R Sahu Jun 07 '15 at 05:15