2

I am learning C++ using the resources listed here. I came across the following claim which I think is incorrect:

typedef int& A;
const A aref = 3; 

because it is equivalent to

int & const aref = 3; 

As you can see in the above code snippet the user claims that const A aref is equivalent to int & const aref. Now, my question is that is the above claim technically correct?

I don't think so. Because the standard specifically says that:

Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name (7.1.3, 14.1) or decltype-specificer (7.1.6.2), in which case the cv-qualifiers are ignored

This means that const A aref = 3; is actually equivalent to:

//---v------------>no const here because it is ignored
int & aref = 3;   //the actual problem is that a non-const lvalue reference cannot bind to rvalue

That is, the actual problem is that "a non-const lvalue reference cannot bind to an rvalue" and not that "we have are applying const to a reference".

So is my analysis correct and the claim by the user is incorrect?

Kal
  • 475
  • 1
  • 16

1 Answers1

2

Your analysis is correct and the claim is incorrect because const A aref = 3; is equivalent to:

int & aref = 3;

which will not work(as you already pointed out in your question) because a non const lvalue reference cannot bind to rvalue.

You can even confirm this using static_assert as shown below:

static_assert(std::is_same_v<const A, int &>); //passes

Demo

This confirms that it is equivalent to int & aref = 3;.

Or even just trying out the code in gcc and you'll get the error saying:

error: cannot bind non-const lvalue reference of type ‘A {aka int&}’ to an rvalue of type ‘int’
Jason
  • 36,170
  • 5
  • 26
  • 60