1

I am interested in the correct semantics of C++ when the -fno-elide-constructors option is used with clang or gcc, and an object is being returned by value. If I have this function and call it:

X foo()
{
    X x(0);
    X y(1);
    X z;
    if (rand() > 50)
        z = x;
    else
        z = y;
    return z;
}

X z = foo();

then I can see that the copy constructor of X is called only once. However, if I modify the function slightly like so:

X foo()
{
    X x(0);
    X y(1);
    if (rand() > 50)
        return x;
    else
        return y;
}

X z = foo();

then the copy constructor is called twice. I can see how this might necessary in the latter case from an implementation perspective but what I find confusing is that it seems that even when we explicitly switch off copy elision there are different numbers of copy constructors being called depending on how the function is implemented.

Is there a section of the standard which covers this behaviour?

maxaposteriori
  • 7,267
  • 4
  • 28
  • 25
  • I'm not getting the same results you are. [Here](http://coliru.stacked-crooked.com/a/983f5afff112991c), it shows that both forms call the copy constructor twice. –  May 25 '14 at 10:33
  • Please add compiler specific tags, as this is mainly about your particukar compiler. – Yakk - Adam Nevraumont May 25 '14 at 12:36

1 Answers1

2

In the first case you see return value optimization, that basically means the compiler allocates z in the return-slot of the function. This won't work in the second case, so you see another copy there. Copy elision is something different: http://en.wikipedia.org/wiki/Copy_elision and does not apply here. The standard just says something like the compiler is free to omit unnecessary copies which allows but does not require either of those optimizations.

pentadecagon
  • 4,717
  • 2
  • 18
  • 26
  • Thanks that clarifies things a bit for me, although this question: http://stackoverflow.com/questions/8758152/disabling-gs-return-value-optimisation seems to imply that the option should switch of RVO as well. – maxaposteriori May 25 '14 at 11:01