Storing value before return in a variable

旧巷老猫 提交于 2019-12-23 05:43:10

问题


Here is a fragment of code:

bool EqualsA(const Foo& a, const Foo& b)
{
    return a == b;
}

bool EqualsB(const Foo& a, const Foo& b)
{
    const bool result = a == b;

    return result;
}

int MethodA()
{
    return GetValue() * GetOtherValue();
}

int MethodB()
{
    const int result = GetValue() * GetOtherValue();

    return result;
}

I wanted to know if there is any difference in returning values in these two different ways (instant return or store result in a variable). I think that storing is better for debugging but is there any performance loss (I don't think there is) or any other pros and cons for using one of those.


回答1:


The compiler is free to optimize away the local variable so the performance is going to be the same.

In a lot of code analysis tools this is marked as a code smell and I would tend to agree. Debuggers can be made to see the return value on the stack so the local variable doesn't buy anything.




回答2:


Under the reasonable assumption that the value returned by the selected overload of operator == for objects of type Foo is of type bool, a decent compiler will optimize your temporary store away when heavy optimization options are used, so as for performance, it does not matter.

My advice is to choose the form that makes your code more readable or more convenient to maintain or debug for you.




回答3:


There will almost certainly be no difference. The compiler is allowed to do whatever it likes to your code as long as the program behaves as-if it were as you wrote it. So any nice compiler will get rid of the pointless initializations.

However, it's possible for there to be a situation it can't make this initialization disappear. If, for example, an operator* overload used for GetValue() * GetOtherValue() returns a class type result by const reference, the constructor of that class type might have some side effects. If it does, the compiler can't get rid of the initialization because it changes the observable behaviour of the program.

But why would that not also be the case if the operator* returned by value? Then this would be a candidate for copy elision, and the compiler could get rid of the construction regardless of whether it had side effects or not.



来源:https://stackoverflow.com/questions/15078153/storing-value-before-return-in-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!