guangzhi
guangzhi

Reputation: 91

IS reference to a reference illegal in C++?

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)

Upvotes: 9

Views: 3807

Answers (5)

R Sahu
R Sahu

Reputation: 206577

"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.

enter image description here

Upvotes: 9

T.C.
T.C.

Reputation: 137330

[dcl.ref]/p1:

In a declaration T D where D has either of the forms

& attribute-specifier-seq_opt D1
&& attribute-specifier-seq_opt D1

and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T,” then the type of the identifier of D is “derived-declarator-type-list reference to T.”

Hence, if the type of the identifier in the declaration T D1 is "reference to T", then the type of the identifier in the declaration T & D1 would be "reference to reference to T". In other words, to attempt to declare a reference to reference, you'd do something like this:

int & & refref = refVal;

However, this code is ill-formed because of [dcl.ref]/p5:

There shall be no references to references, no arrays of references, and no pointers to references.

There's a separate rule in the standard that says that if TREF is a typedef for T&, then when you try to do TREF&, instead of failing because of the rule above, the references would collapse so that TREF& actually means T&. A similar collapsing rule applies to decltype(...). This rule does not apply when you are trying to declare a reference to reference directly.

Upvotes: 1

CreativeMind
CreativeMind

Reputation: 917

Your code

int &refVal2=refVal; 

is perfectly valid and fine.

Illegal code would be:

int &&refVal2=refVal;

Upvotes: 0

hyde
hyde

Reputation: 62797

Your code does not have a reference to reference.

int &refVal2

Clearly a reference to integer, is it not?

Upvotes: 1

Brian Bi
Brian Bi

Reputation: 119154

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&(&).

Upvotes: 14

Related Questions