Storing value before return in a variable

2019-06-13 04:29发布

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.

3条回答
做个烂人
2楼-- · 2019-06-13 04:39

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楼-- · 2019-06-13 04:43

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.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-06-13 04:55

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.

查看更多
登录 后发表回答