0

The following code generates output:

copy constructor: i = 2

I don't understand why the copy constructor doesn't get called returning from f1(). I'm using Visual C++ V12. I thought it might be return value optimization but I get the same output whether I'm compiling Debug or Release.

class C
{
public:

    C(int i) { i_ = i; }

    C(C const &rhs)
    { 
        i_ = rhs.i_;
        std::printf("copy constructor: i = %i\n", i_);
    }

    int i_;
};

C f1()
{
    return C(1);
}

C f2()
{
    C c(2);
    return c;
}

int main()
{
    C c1 = f1();
    C c2 = f2();
    return 0;
}
George Skelton
  • 1,095
  • 1
  • 10
  • 22
  • 1
    [Copy ellision](http://stackoverflow.com/q/12953127/27678) – AndyG Jun 24 '16 at 18:58
  • 1
    Where is it stated that `Debug` mode turns off copy elision? – PaulMcKenzie Jun 24 '16 at 18:58
  • See also: [why isn't the copy constructor called](http://stackoverflow.com/questions/14154290/why-isnt-the-copy-constructor-called) (bet you could have found this by searching) – Cody Gray - on strike Jun 24 '16 at 18:59
  • debug mode doesn't mean zero optimization. – UmNyobe Jun 24 '16 at 19:00
  • 1
    RVO (and copy elision in general) shouldn't be thought of as an optimization, despite what the O stands for. It changes the behavior of the program. The behavior of a correct program should not change based on optimization level. And so compiler authors will perform copy elision regardless of optimization level. – Benjamin Lindley Jun 24 '16 at 19:02
  • All Debug mode gives you is the "guarantee" that the lines in your source code match up with the little highlight that moves up and down when you step in the program. If for some reason that highlight went into your copy constructor code and you noticed that it really wasn't being called, then you would have a case. – PaulMcKenzie Jun 24 '16 at 19:07
  • Thanks everyone for the helpful links and comments – George Skelton Jun 24 '16 at 19:20

0 Answers0