Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to reference is not allowed in ISO C++ 2003 standard, but why it is allowed by compilers?

According to ISO C++ 2003 standard section 8.3.2

"references to references are not allowed"

But I have tried following code in Visual C++ and Ideone, and both compilers are running this code successfully.

Ideone GCC C++4.3.2

int main() 
{
    int i=2;
    int &ref_i=i;
    int &ref_ref_i=ref_i; // should be an error according to c++ 2003 standard

    cout<<i<<endl<<ref_i<<endl<<ref_ref_i;  
    return 0;
}

I am really confused after looking at this behavior of compilers; can someone explain this?

like image 784
Neha Avatar asked Jul 27 '14 07:07

Neha


People also ask

Can reference be modified?

Formally speaking, that is impossible as it is forbidden by design. Arbitrarily speaking, that is possible. A references is stored as a pointer, so you can always change where it points to as long as you know how to get its address.

What is the point of references in C++?

The main use of references is acting as function formal parameters to support pass-by-reference. In an reference variable is passed into a function, the function works on the original copy (instead of a clone copy in pass-by-value).


Video Answer


1 Answers

You do not create a reference-to-reference in your code.

It is just another int&, i.e. both are references to an int

(T.C. shows an example of an illegal C++03 reference to reference)


The C++11 Standard section § 8.3.2 explicitly shows this by an example (disallowing references of references, of course, did not change between C++03 and C++11, but reference collapsing is new in C++11) :

If a typedef-name (7.1.3 , 14.1) or a decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a type T, an attempt to create the type “lvalue reference to cv TR” creates the type “lvalue reference to T”, while an attempt to create the type “rvalue reference to cv TR” creates the type TR.

int i;
typedef int& LRI;
typedef int&& RRI; 

LRI& r1 = i; // r1 has the type int&
const LRI& r2 = i; // r2 has the type int& 
const LRI&& r3 = i; // r3 has the type int&
like image 68
quantdev Avatar answered Oct 18 '22 15:10

quantdev