D
Dave O'Hearn
Gary said:You got me thinking; isn't a reference more like a #define that
has scope?
What I mean is: #define ref x
would do what int &ref = x;
does EXCEPT with define there is no scope or type checking. In
other words, whenever the compiler sees ref, it uses x.
If so, couldn't a compiler implement the references by precompiling
them with the substitution, adding #defines to set and unset the
variable and then compile as normally? This would be a lot of
overhead, of course, but would it give the same result?
It makes sense for objects that have names, but not all objects have
names. Like this,
int* ip = new int;
int& ir = *ip;
delete ip;
I think the "alias" view is counterintuitive on this. It makes sense to
say the reference declares a name for an object, but "alias" suggests
the object had a name to start with, which is not always the case. The
delete operation also shows that references can be invalid the same way
pointers can be, so a reference is just as likely to have a runtime
representation as a pointer is, even if technically that representation
is not considered "storage".
Another oddity is sizeof. sizeof(T&) is equivalent to sizeof(T). "Alias
without storage" suggests it would be invalid, while "like a pointer,
but" suggests it would be sizeof(T*). Neither explanation helps. sizeof
just has to be kept in mind as odd.