Why is adding a reference to a rvalue reference not an error? [duplicate]
Asked Answered
O

1

15

I have the following typedef:

using int_ref = int&&;

Why does the following code not produce an error (or print false)?

std::cout << is_same< int_ref, int_ref&& >::value; // prints 1

I would expect that int_ref&& gets expanded to int&& && which is obviously not possible. Am I missing something?

Ouzel answered 8/6, 2016 at 11:10 Comment(0)
F
28

This is due to reference collapsing rules.

Basically, although you can't write a reference to a reference yourself, in some cases (typedefs, template parameters, decltypes) you can add create a reference to a reference type, which collapses as follows:

A& & -> A&
A& && -> A&
A&& & -> A&
A&& && -> A&&

In your case, int_ref is int&&, so int&& && becomes int&&.


The relevant standard quote:

(N3337) [dcl.ref]/6: If a typedef (7.1.3), a type template-parameter (14.3.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.

Felicidadfelicie answered 8/6, 2016 at 11:15 Comment(3)
Ah, cool! Do you, by any chance, have a reference to the c++ specification where this is mentioned?Ouzel
@Ouzel Sure, addedFelicidadfelicie
@Ouzel If you've ever heard someone talk about "universal references" or "forwarding references", that's the simplified explanation of reference collapsing that many people find more intuitive and useful in practice. You've found one of the few corner cases where it doesn't work.Flump

© 2022 - 2024 — McMap. All rights reserved.