-1

Since it is not possible to define a reference to a reference, why is the 8th line of this code not throwing an error? My understanding is that the aforementioned statement is equivalent to double &&ref2 = value; which should throw an error.

#include <iostream>
using namespace std;
int main()
{
    double value = 12.79;
    typedef double& ref_to_double;
    ref_to_double ref = value;        // Equivalent to double &ref = value;
    ref_to_double &ref2 = value;      
    ref2 = 12.111;
    cout << value << endl;        
}

Output:

12.111

Follow-up question: Replacing the 8th line with ref_to_double &&ref2 = value; is also not producing a compile-time error. Why is this so?

Bran
  • 29
  • 1
  • 5
  • 1
    AFAIK, it is not equivalent to `double && ref2`, but to `double & & ref2`, which is equivalent to `double & ref2` due to [_reference-collapsing_ rules](https://en.cppreference.com/w/cpp/language/reference). Similarly, `ref_to_double &&`, that is `double & &&`, collapses to `double &` as well. – Daniel Langr May 31 '21 at 05:58
  • 1
    Reference collapsing: https://stackoverflow.com/questions/13725747/concise-explanation-of-reference-collapsing-rules-requested-1-a-a-2 – Amir Kirsh May 31 '21 at 06:01
  • Isn't the `double &&` the r-value reference? Though, topic starter didn't clarify the C++ standard. – Serge Roussak May 31 '21 at 06:04
  • @SergeRoussak It is, but `ref_to_double &&`, that is `double & &&`, is not. – Daniel Langr May 31 '21 at 06:07

1 Answers1

1

Why is it possible to define a reference to a reference using type alias?

is also not producing a compile-time error. Why is this so?

why is the 8th line of this code not throwing an error?

Because the language allows such expressions to be valid, there is no other explanation... Let's take the nice example from the standard, from c++draft/Declarations/References:

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&

RRI& r4 = i;                    // r4 has the type int&
RRI&& r5 = 5;                   // r5 has the type int&&

decltype(r2)& r6 = i;           // r6 has the type int&
decltype(r2)&& r7 = i;          // r7 has the type int&
KamilCuk
  • 120,984
  • 8
  • 59
  • 111