I was just wondering what typically happens under the hood when you
pass a C++ variable by reference. It looks like a pointer gets passed
in, but the compiler let's you access it as if it wasn't a pointer.
Anyone know if this is how it's always done?
To think of a reference as a pointer is not healthy.
The best way to explain a reference is by examining references from the
same perspective as he who created C++ (Bjarne Stroustrup). After all,
it was his idea. You might consider looking up his explanation of the
reference.
If you declare a variable n:
int n(5); // or int n = 5;
n is a reference to what would otherwise have been an *anonymous*
allocation of a specific type. It basicly sets aside a name or
identifier that is permanently linked to that allocation. So, on the
outset, n is technically already a reference. Just like:
int& r(n); // r is itself a reference to n
The difference between a reference and a pointer is best examined by
considering the following:
// a constant pointer to a mutable object
int* const p_n = &n;
I can modify what is *at* p_n but i cannot reseat p_n to point to
another variable. The same applies to a reference. Note that a
reference that "refers" to a null value or an invalid value is
undefined behaviour. The same is not true of a pointer. Pointers are
dumb. A pointer can be nullified, it can point to nothing in particular
and it can be casted, etc.
A pointer has a value - it stores an address and all it knows is that
its got a type. A reference's "value" is obtained from its referred_to
object. A reference's address is again the referred_to object's
address.
Bottom line is that a reference and a pointer (even a const ptr) have
very little in common.