Can ?: lead to less efficient code compared to if/else when returning an object?
Foo if_else()
{
if (bla)
return Foo();
else
return something_convertible_to_Foo;
}
If bla is false, the returned Foo is directly constructed from something_convertible_to_Foo.
Foo question_mark_colon()
{
return (bla) ? Foo() : something_convertible_to_Foo;
}
Here, the type of the expression after the return is Foo, so I guess first some temporary Foo is created if bla is false to yield the result of the expression, and then that temporary has to be copy-constructed to return the result of the function. Is that analysis sound?
A temporary
Foohas to be constructed either way, and both cases are a clear candidate for RVO, so I don’t see any reason to believe the compiler would fail to produce identical output in this case. As always, actually compiling the code and looking at the output is the best course of action.