suppose I have
typedef int& intr;
typedef intr& intrr;
I am allowed to declare
int x = 7;
intrr y = x;
But what is a reference-to-reference? Is an intrr any different semantically than just an intr?
suppose I have
typedef int& intr;
typedef intr& intrr;
I am allowed to declare
int x = 7;
intrr y = x;
But what is a reference-to-reference? Is an intrr any different semantically than just an intr?
There's no such thing as a reference to reference. The C++ standard explicitly says so:
§8.3.3/5
There shall be no references to references, ...
In typedefs and templates, there is a rule commonly referred to as "reference collapsing". It's described in paragraph 6 of the same section:
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 typeT
, an attempt to create the type “lvalue reference to cvTR
” creates the type “lvalue reference toT
”, while an attempt to create the type “rvalue reference to cvTR
” creates the typeTR
.[ Example:
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&
— end example ]
intr
and intrr
in your sample are exactly the same type, which is int&
.
#include <iostream>
#include <type_traits>
int main()
{
typedef int& intr;
typedef intr& intrr;
int x = 7;
intrr y = x;
std::cout << std::is_same<intr, intrr>::value;
std::cout << std::is_same<int&, intrr>::value;
std::cout << std::is_same<int&, intr>::value;
}
Output: 111
Thomas Becker's article on Rvalue References explained provides a nice table:
- A& & becomes A&
- A& && becomes A&
- A&& & becomes A&
- A&& && becomes A&&