Re: Portability and legality of resetting references (changing underlying pointer)
Edson Manoel <e.tadeu@gmail.com> wrote in news:1189034997.635349.245700
@d55g2000hsg.googlegroups.com:
Ok, reinterpret_cast is not portable; what about using unions (see
following code) -- are references always guaranteed to be stored as a
single pointer? Is it safe to assume this? Is there a safe way to
reset a reference?
The analogy I like to use for references is that a reference is to an
object as a typedef is to a type. That is, if you have:
typedef std::vector<int> MyVector;
Then when you see MyVector, you could just has easily have substituted
std:::vector<int> and visa versa. That is because typedef (inspite of
it's name) just creates another name for the type specified. A similar
thing happens with references. If you see:
int a;
int & b = a;
Then everywhere you see a 'b', you can think 'a'. In fact, I don't know
of any compiler which will generate any sort of backing for 'b' in this
case. The code generated will all access 'a'.
If you want to reseat what a variable points to, then get over your
prejudices and use a pointer. That is what they are for. I think what
adds to the confusion is Java/C# use of 'references' instead of
pointers. In Java-like syntax, you can have:
Object a = new Object;
a = new Object;
And what would happen is that 'a' would now refer to the second object
and the first would be garbage collected. In C++, if you had:
Object & a = *new Object;
a = *new Object;
What would happen (if all the operators were in place) is that the
contents of the second object would be copied into the first object and
the second object would be orphaned. What you want instead in C++ is:
Object * a = new Object;
delete a;
a = new Object;
If you used an auto_ptr<> instead:
std::auto_ptr<Object> a(new Object);
a.reset(new Object);
As you can see, the above lines are hugely different from the Java/C++
references. Furthermore, in Java/C#, references can be empty (i.e. a
null pointer) so you would even lose the non-null guarantee that
references currently have.
My recommendation would be to use the language as it is and don't spend
a lot of time trying to make it look like something else. If it's that
important to you to use '.' instead of '->' in all cases, then look at
Java or C#.
joe
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]