Can the conditional operator lead to less efficient code?

Viewed 448

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?

6 Answers
Related