Why returning FVector by copy?


In a lot of places, I see you return FVector by copy. Shouldn’t it be more efficient to return FVector by const reference instead?

In AActor::GetComponentLocation() or Actor::GetActorLocation() for example.

Thanks for the explanations

These functions are carefully crafted so that the compiler will eliminate the function’s local return value. There will be no extra copy. The results will go straight into the value being assigned to. This is a compiler optimization called Return Value Optimization (RVO).

In case you’re interested, similar optimizations can be achieved for values passed into the function. See also c++ - How true is "Want Speed? Pass by value" - Stack Overflow

Thanks for your answer.

In the wikipedia page you linked, it is said there are circumstances where RVO can not happen : Copy elision - Wikipedia

Apparently, USceneComponent::GetComponentLocation looks like to be such a case?

Are there so much benefits (performance? memory?) of returning copies of FVector and relying on RVO, instead of returning const references? (BTW, can RVO happen with const references?)

One caveat I can see is the lack of the semantic. With a const reference, you know for sure you don’t have a copy, whereas using the RVO, you have at least to be aware of the compiler optimization :slight_smile:

Whether Visual Studio can do RVO on USceneComponent::GetComponentLocation(), I do not know. Best way to find out is to look at the assembler code. I think that it will probably still be able to figure it out in this case by evaluating const semantics, but it’s probably a good topic for the compiler geeks here.

As far as semantics go, returning by value and return by reference are actually pretty clear cut. When you return a reference, you allow the caller to see changes that the callee may make to the value. The const specifier only prevents the caller from modifying that value itself.

When you return a value, then you don’t allow the caller to see changes that the callee may make internally. From this point of view, the above functions should clearly be returning by value.

You should be able to find many discussions about this on the internet. I think the general consent is that return by value should be used for (simple) value types.