1

I have the following code:

#include <iostream>
using namespace std;

class X
{
public:
    int g;
    X() { cout << "constr" << endl; }
    X(const X& ref1) { cout << "copy constr" << endl; }
};

X f()
{
    X ee;
    ee.g = 1;
    return ee;
}

int main()
{
    X ff = f();
    return 0;
}

Running the code I see that the constructor was called only once and the copy constructor was never called. Don't you expect two constructor and one copy constructor calls here? Thanks!

hovnatan
  • 1,331
  • 10
  • 23

2 Answers2

1

This is a special case of the copy elision called return value optimization (the link explains precisely your case).

bobah
  • 18,364
  • 2
  • 37
  • 70
0

Copy Elision is an optimization implemented by many compilers to prevent extra, unnecessary, copies. Makes the return-by-value or pass-by-value possible in practice.

Take a look at the example in the following answer: https://stackoverflow.com/a/12953129/1938163

struct C {
  C() {}
  C(const C&) { std::cout << "A copy was made.\n"; }
};

C f() {
  return C();
}

int main() {
  std::cout << "Hello World!\n";
  C obj = f();
}

(http://en.wikipedia.org/wiki/Return_value_optimization#Summary)

Perhaps incredible to believe the first time, depending on the compiler & settings, the following outputs are all valid:

Hello World! 
A copy was made. 
A copy was made. 

Hello World! 
A copy was made.

Hello World!

In your case, this is a special copy elision optimization called RVO - Return Value Optimization where an object returned by value from a method has its copy elided.

Community
  • 1
  • 1
Marco A.
  • 43,032
  • 26
  • 132
  • 246
  • when cut/pasting from Wikipedia you [normally](http://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License) mention this explicitly – bobah Mar 08 '14 at 18:21
  • 1
    I posted the link entirely, but I'll mention it if you want. – Marco A. Mar 08 '14 at 18:22