int main(){
int ival=1024;
int &refVal=ival;
int &refVal2=refVal;
return 0;
}
C++ Primer(5th edition) says "Because references are not objects, we may not define a reference to a reference."(Chinese 5th version says "不能定义引用的引用".meaning can't define a reference to a reference. )
But I got the code above pass compilation.
What's going on?
Feel free to correct any errors(including my English skills)
A reference is an alias to the object itself. So when you try to make a reference to a reference, the reference passes it on to the object itself so you end up with just another reference to the object.
C++ references differ from pointers in several essential ways: It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references. Once a reference is created, it cannot be later made to reference another object; it cannot be reseated.
Remember, once you initialize a reference, you cannot reassign it. A reference practically stands for an object. You cannot make it 'point' to a different object.
Easy To Learn Reference operator (&) In C Language. This referencing operator is also called address operator, which gives the address of a variable, in which location the variable is resided in the memory.
After refVal
is initialized, whenever you mention its name, it behaves like the variable ival
it refers to---its "referenceness" can no longer be detected (except by decltype
). Therefore refVal2
is simply initialized to refer to ival
also.
There is no type "reference to reference to int
", int&(&)
.
"Because references are not objects, we may not define a reference to a reference."
Perhaps they meant to say:
int i = 10;
int& ref1 = i;
int&& ref2 = ref1; // Not allowed.
Of course, in C++11, the symbol &&
is used to define rvalue references.
I think it's more illustrative to compare references and pointers to understand why references to references does not make sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With