A reference in C++ is exactly that, it's a variable name that refers to some other variable.
Think in terms of the statements:
int xyzzy = 1;
int &plugh = xyzzy;
int twisty = xyzzy;
The actual "object" here for xyzzy
is the thing containing the value 1
. You refer to it by its name xyzzy
but that's really just a name for it.
The plugh
is another reference to exactly the same underlying object - changing the value of plugh
will also change the value of xyzzy
since those are both names of (references to) the same thing.
The twisty
variable, on the other hand, is created as a new object and simply copies the value of xyzzy
across to it.
You'll often see things like:
void fn(const string &str1) { ... }
in code since it's more efficient to pass a reference to an object that's relatively expensive to construct/copy (like a string). Passing a reference to the object allows you direct access to the currently existing object, and making it const
prevents the function from changing it.
It's very unusual to see this done with a basic type like int
since the cost of duplicating them is very small, usually about the same as the cost of passing a reference to them.
You will occasionally see things like:
void fn(int &thing) { ... }
but that's usually because the thing
is expected to be changed in the function and that change get mirrored back to the caller.
What your particular code is probably doing (though I can't be sure without more context) is not creating any new object, by virtue of the return of a reference. The following code shows, in my best guess, the sort of implementation it would have:
const int& GetMax(const int& value1, const int& value2) {
if (value1 >= value2)
return value1;
return value2;
}
With that, the code:
int val1 = 7;
int val2 = 42;
const int &biggest = GetMax (val1, val2);
will actually set the reference biggest
to refer to the largest of val1
and val2
. In other words, it's functionally equivalent to the pseudo-code:
val1 = 7
val2 = 42
if (val1 > val2)
biggest = reference to val1
else
biggest = reference to val2