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?
Difference between if-else statement and ternary operator: The ternary operator is a statement in JavaScript, and a statement is faster than Block. The if-else is a programming block. The ternary operator is more efficient and readable.
It is not faster. There is one difference when you can initialize a constant variable depending on some expression: const int x = (a<b) ?
Conditional operators are used to evaluate a condition that's applied to one or two boolean expressions. The result of the evaluation is either true or false.
The conditional operator is kind of similar to the if-else statement as it does follow the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible.
A temporary Foo
has 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.
It most definitely can where rvalue references are enabled. When one of the two branches is an lvalue and the other an rvalue, whichever way you go, you're going to not get the correct function called for at least one of them. When you do the if statement way, then the code will call the correct move or copy constructor for the return.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With