Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decltype - "the only context in which a variable defined as a reference is not treated as a synonym for the object to which it refers"?

Tags:

c++

I'm reading C++ Primer, 5th Ed., where on p. 71 they first give this code example:

const int ci = 0, &cj = ci;
decltype(ci) x = 0;
decltype(cj) y = x;
decltype(cj) z; //error

Then they say:

It is worth noting that decltype is the only context in which a variable defined as a reference is not treated as a synonym for the object to which it refers.

What do they mean by this? I don't get it. The y there refers to x. So what's the catch?

like image 683
Dennis Ritchie Avatar asked Jan 16 '13 17:01

Dennis Ritchie


1 Answers

I believe they're trying to say that decltype(cj) will not give you the type of the object that cj refers to (that is, const int) but will give you the type of cj itself. So y will be const int&.

The case to compare this to is when using the name of a reference in an expression. The standard says:

If an expression initially has the type “reference to T” (8.3.2, 8.5.3), the type is adjusted to T prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.

That is, when using the name of a reference in an expression, it is not the reference that is acted on but the object it refers to. This is what gives a reference type the functionality of an "alias".

like image 182
Joseph Mansfield Avatar answered Nov 15 '22 13:11

Joseph Mansfield