Why does the ternary operator prevent Return-Value Optimization (RVO) in MSVC? Consider the following complete example program:
#include <iostream>
struct Example
{
Example(int) {}
Example(Example const &) { std::cout << "copy\n"; }
};
Example FunctionUsingIf(int i)
{
if (i == 1)
return Example(1);
else
return Example(2);
}
Example FunctionUsingTernaryOperator(int i)
{
return (i == 1) ? Example(1) : Example(2);
}
int main()
{
std::cout << "using if:\n";
Example obj1 = FunctionUsingIf(0);
std::cout << "using ternary operator:\n";
Example obj2 = FunctionUsingTernaryOperator(0);
}
Compiled like this with VC 2013: cl /nologo /EHsc /Za /W4 /O2 stackoverflow.cpp
Output:
using if:
using ternary operator:
copy
So apparently the ternary operator somehow prevents RVO. Why? Why would the compiler not be clever enough to see that the function using the ternary operator does the same thing as the one using the if statement, and optimize accordingly?