G-Fact 25
July 23, 2010
In C++, Reference variables are safer than pointers because reference variables must be initialized and they cannot be changed to refer to something else once they are initialized. But there are exceptions where we can have invalid references.
1) Reference to value at uninitialized pointer.
int *ptr; int &ref = *ptr; // Reference to value at some random memory location
2) Reference to a local variable is returned.
int& fun()
{
int a = 10;
return a;
}
Once fun() returns, the space allocated to it on stack frame will be taken back. So the reference to a local variable will not be valid.
Please write comments if you find anything incorrect in the above GFact or you want to share more information about the topic discussed above.


Why should a reference refer to pointer type? From the notes of Stroustrup “A reference is an alternative name for an object. The main use of references is for specifying arguments and return values for functions in general and for overloaded operators in particular.”
In the example, the reference can’t be invalid where as the referred entity can be. I believe they should be used carefully. An example, the following won’t even compile
It is possible only with reference (as mentioned above)
T &operator++(T &t) { t = (T)(t + 1); return d; }There are many ways we can misuse references,
int& fun() { int a = 10; return a; }However, reference types are guaranteed by compiler to refer same entity to which it was binded, even in case function arguments.
An invalid reference is also possble when you have a valid pointer and the space allocated to pointer is deleted later.