A reference refers to an object instance somewhere else. When you use a reference to an object, all uses of that reference are as though you are using that original object. This allows one T&
to reference another T&
, etc -- but eventually it will have to reference an existing T
object from somewhere.
This answers the "why does it work" part of your question; because a reference simply refers to the instance itself.
The answer to your other question of "what is the real difference between these two" is a little more complicated. const
references in C++ are a little weird in that they are capable of extending the lifetime of temporary objects.
All objects in C++ have lifetime. Ordinarily, the lifetime of an object starts when they are created, and ends at the end of their scope -- whether this is just all part of an expression, or up to the literal ending }
scope. References view that lifetime, but don't normally affect the lifetime (which means that returning a reference to a temporary, for example will produce a dangling reference to an object that is no more).
const
references, on the other hand, extend the lifetime to the length of the enclosing scope. So when you have:
const int& a1 {2};
const int& a2 {20};
What you are actually doing is creating two temporary unnamed objects with values 2
and 20
, and the const int&
is extending the lifetime of these variables.
This is as if you did something like:
const int __unnamable_value_1 = 2;
const int __unnamable_value_2 = 20;
const int& a = __unnamable_value_1;
const int& b = __unnamable_value_2;
For the most part, I would recommend not thinking about this weirdness of C++. If you want to create a named value, create it by value (e.g. const T
). If you want to refer to an object possibly not constructed in the same place, use a reference (const T&
).