* Tom Payne, on 12.11.2010 07:02:
Consider the code:
int n = 3;
int& g() { return n; }
Visibly g() return a reference to an integer, and g() returns n. Does
it not follow that n is a reference to an integer?
As far as C++ is concerned there's no way to differentiate a reference to 'n'
from 'n' itself.
So technically, at the level of observable effects, disregarding insights that
may be gleaned from timing the execution or inspecting the machine code or such,
yes. This also follows from the view of C++ references as simple aliases. It's a
view that holds for valid programs...
However, conceptually we think in terms of original object and external
references to it. And that's also what the compiler has to do. And when you have
an invalid program, one that e.g. produces a dangling references (such as a
function returning a reference to non-static local variable), then the
equivalence between references and the objects that they refer to, breaks down.
So, in order to be able to reason about validity of programs, one must also
consider that references are sort of secondary.
It is a common problem in teaching and learning programming, that the same term,
referring to essentially the same thing, still can mean subtly different things
depending on the context that is assumed in one's head (e.g. here, am I talking
about valid C++ programs, or am I considering validity, or am I thinking about
how it's translated to machine code, or what). And often, in discussions, such
context is just assumed, implicitly. I think the worst example I've experienced
was a person who steadfastly maintained that it was meaningless to talk about
"the current thread". Notwithstanding that the API being discussed had a
function GetCurrentThread. It turned out to be impossible to convince that
person that a meaningful interpretation could exist, and I gave up when the
percentage of innuendo and ad hominem reached 99%.
Cheers & hth.,
- Alf