Because the declaration was const FString&
That it is a reference. As previously stated that is covered later. However if you want to get ahead of yourself continue reading otherwise stop here.
void UBullCowCartridge::OnInput(const FString Input);
This is known as “passing by value” and would mean a copy of the FString
. For primitive types this is completely fine and the most performant option as they are cheap to copy. An FString however, is not cheap to copy.
When you create an FString
it will dynamically allocate memory in which to store the string (sometimes more than you initially need so you can append more characters to it). At then at the end of its lifetime would need to free that memory.
When you copy it you will have to do the same thing. Allocate enough to store the string and then copy each character over to the new string then free that memory when it goes out of scope.
So for this function to pass by value you would copy the string over, do nothing but read it, then free the memory that was allocated at the end of the function.
If all you need is to read it then const T&
lets you do that without copying.
See this example: Compiler Explorer
The passed in value is in fact the same object.
Parameter passing advice: C++ Core Guidelines
To expand on my initial answer
void foo(int);
void foo(const int);
These two declarations (note: not the definition) are in fact the same thing. As from the callers perspective it makes no difference whether the function doesn’t modify their copy or not. Why would the caller care what the definition does with their own copy? The object on the callers side will remain the same regardless.
void foo(int&);
void foo(const int&);
In contrast these two function declarations are different, importantly so. As the first one can modify the object that was passed in.
void foo(int& n)
{
n = 10;
}
int main()
{
int value = 25;
foo(value);
// value == 10
}
It also means you can’t pass in const
variables
void foo(int& n)
{
// do nothing with n
}
int main()
{
const int value = 25;
foo(value); // compilation error
}
Because non-const reference is saying “I will modify” even if it doesn’t actually modify it.