条件运算符会导致代码效率降低吗? [英] Can the conditional operator lead to less efficient code?

查看:322
本文介绍了条件运算符会导致代码效率降低吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当返回对象时,<$> ?<:$ 会导致效率低于 >

  Foo if_else()
{
if(bla)
return Foo
else
return something_convertible_to_Foo;
}

如果 bla false,返回的 Foo 直接从 something_convertible_to_Foo 构造。

  Foo question_mark_colon()
{
return(bla)? Foo():something_convertible_to_Foo;
}

这里,返回后的表达式类型 Foo ,所以我想先创建一些临时 Foo c> bla 是false以产生表达式的结果,然后该临时必须被复制构造以返回函数的结果。这个分析是否有声音?

解决方案

必须构造一个临时 Foo 任何一种方式,这两种情况都是RVO的一个明显的候选人,所以我没有看到任何理由相信编译器将无法产生相同的输出在这种情况下。和往常一样,实际编译代码并查看输出是最好的做法。


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 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆