Noel Widmer
Noel Widmer

Reputation: 4572

C++ Is this an "invalid" reference after returning?

This is obviously bad:

int& GetInvalidIntPtr(){
   int i;
   return i;
}

This is my example:

FVector& GetDirectionFromCamera(){ 
   return GetActorLocation() - GetCameraComponent()->GetComponentLocation(); 
}

An FVector basically holds 3 floats, that is why I'd like to return the reference rather than a copy. However, I believe the result of the calculation is stored on the stack, right?
Or is the result allocated on the heap because I am immediatly returning it?

Upvotes: 0

Views: 106

Answers (2)

Christian Hackl
Christian Hackl

Reputation: 27548

An FVector basically holds 3 floats, that is why I'd like to return the adress rather than a copy.

If you'd like to return an address, then why do you do return a reference instead? References are not pointers.

(Deleted because the question has been modified to use the word "reference" instead of "address".)


However, I believe the result of the calculation is stored on the stack, right?

It really depends on what exactly your operator- returns. You don't show us, so we cannot know for sure, but if the operator simply returns FVector (as it should), then your code cannot compile, because a temporary FVector cannot be used to initialise an FVector&.

Generally, your code is based on the misconception that it's somehow bad to return a copy of an FVector. It is not. Change the function signature to FVector GetDirectionFromCamera() and let the compiler remove redundant copies.

Or is the result allocated on the heap because I am immediatly returning it?

No. What you call "heap" only comes into play when you use dynamic allocation.

Upvotes: 1

Jonathan Wakely
Jonathan Wakely

Reputation: 171491

Or is the result allocated on the heap because I am immediatly returning it?

What? How would that even happen? The compiler does not just magically allocate things on the heap because you return something that's going out of scope.

Trying to optimise away a copy of three floats, at the risk of undefined behaviour because you don't understand what the code is really doing, is insanity. If you don't know any better then just return a copy. That's the simple and safe option. It's also likely to be the fastest, because simple code allows the compiler to optimise better.

Upvotes: 2

Related Questions