0
#include <iostream>
using namespace std;

class X
{
public:
    X() { cout<<"default constructor"<<endl; }
    X(const X&) { cout<<"copy constructor"<<endl; }
};

X test(X a)
{
    X y = a;
    return y;
}

int main()
{
    X obj;

    X obj1 = test(obj);
    return 0;
}

Output:

default constructor
copy constructor
copy constructor

I had compiled the using MinGw compiler.

But, I think the output is wrong. The copy constructor is called when an object is passed by value, return by value or explicitly copied. In the above program, the "copy constructor" has to be called 4 times.

  1. test(obj) is called, to copy obj to a
  2. X y = a is called, explicitly copied.
  3. return y is called, y is copied to a temporary object, let it be temp
  4. X obj1 = temp, explicitly copied.

Please correct me. Provide your justification too..

David Hammen
  • 32,454
  • 9
  • 60
  • 108
  • Please add a language tag, if appropriate. You'll also get automatic syntax highlighting ;) – dyp Dec 19 '13 at 19:34

2 Answers2

3

This is an example of the so-called "return value optimization."

The compiler notices that it will have to copy the value of y to obj1, so instead of returning it by value and copying it to obj1, it has the function test write to obj1 directly.

See http://en.wikipedia.org/wiki/Return_value_optimization.

Andrey Mishchenko
  • 3,986
  • 2
  • 19
  • 37
1

This is an example of (N)RVO, aka Named Return Value Optimization. The compiler is allowed to elide the copy in the following code:

X test(X a)
{
X y = a;
return y;
}

If you had written something like this instead:

X test(X a)
{
X x = a;
X y = a;
return (true ? x : y);
}

(N)RVO would not apply.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770