Why would I need a Reference?

In the video we are given an example:

float Damage = 0;
float& DamageRef = Damage;
DamageRef = 22;
UE_LOG(LogTemp, Display, TEXT("DamageRef:  %f, Damage: %f"), DamageRef, Damage);

Why bother creating a reference call DamageRef? Can I not just use Damage? I don’t see any advantage here when just using Damage would require less typing and uses less lines of code. The video didn’t really give me a good use case for referencing.

For a local variable it doesn’t make sense as you note. It’s when passing to an from functions.

Consider the following code:

void Print(FString Msg);

void Foo()
{
    FString Name = TEXT("Dan");
    Print(Name);
}

Here Print takes the parameter “by value” which means to copy. FString stores a dynamically sized string, which when you copy one you’ll have to dynamically allocate enough memory to hold the new string then copy each character over. Then when that object goes out of scope that memory will be freed.

Assuming Print does exactly what it says, did it need a copy? Did it really need to do that work when all it will do is read the string? That’s where references comes in, now you aren’t dynamically allocating memory and copying all of the characters over, and in this example it should also be const & as it would be rather surprising if a print function modified what I passed to it.

Thank you. This has made things much clearer.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms