Why does the ternary operator prevent Return-Value Optimization (RVO) in MSVC? Consider the following complete example program:
#include
st
This related question contains the answer.
The standard says when copy or move elision is allowed in a return statement: (12.8.31)
So basically copy elision only occures in the following cases:
If your expression is not a named object or a temporary, you fall back to copy.
Some Interesting behaviors:
return (name);
does not prevent copy elision (see this question)return true?name:name;
should prevent copy elision but gcc 4.6 at least is wrong on this one (cf. this question) EDIT:
I left my original answer above but Christian Hackl is correct in his comment, it does not answer the question.
As far as the rules are concerned, the ternary operator in the example yields a temporary object so 12.8.31 allows the copy/move to be elided. So from the C++ language point of view. The compiler is perfectly allowed to elide the copy when returning from FunctionUsingTernaryOperator.
Now obviously the elision is not done. I suppose the only reason is that Visual Studio Compiler team simply did not implement it yet. And because in theory they could, maybe in a future release they will.
Looking at the program output, it seems to me that, indeed, the compiler is eliding in both cases, why?
Because, if no elide was activated, the correct output would be:
So, I would expect, at least 2 "copy" output in my screen. Indeed, If I execute your program, compiled with g++, with -fno-elide-constructor, I got 2 copy messages from each function.
Interesting enough, If I do the same with clang, I got 3 "copy" message when the function FunctionUsingTernaryOperator(0);
is called and, I guess, this is due how the ternary is implemented by the compiler. I guess it is generating a temporary to solve the ternary operator and copying this temporary to the return statement.
I can see that it violates one general rule about RVO – that the return object (should) be defined at a single position.
The snippet below satisfies the rule:
Example e;
e = (i == 1)? Example{1} : Example{2};
return e;
But in the original expression like below, two Example
objects are defined at two different positions according to MSVC:
return (i == 1) ? Example(1) : Example(2);
While the conversion between the two snippets is trivial to humans, I can imagine that it doesn't automatically happen in the compiler without a dedicated implementation. In other words, it's a corner case which is technically RVO-able but the devs didn't realize.