引用到引用在C++中是什么意思?(不是右值引用)

What does a reference-to-reference mean in C++? (Not an rvalue reference)

本文关键字:引用 意思 C++ 是什么      更新时间:2023-10-16

>假设我有

typedef int& intr;
typedef intr& intrr;

我可以声明

int x = 7;
intrr y = x;

什么是引用到引用?intrr在语义上与intr有什么不同吗?

没有引用这样的东西。C++标准明确指出:

§8.3.3/5

不得引用参考文献,...

在 typedefs 和模板中,有一个规则通常称为"引用折叠"。同一部分的第 6 段对此进行了描述:

如果是 typedef (7.1.3)、类型模板参数 (14.3.1) 或 decltype-specifier (7.1.6.2) 表示一个类型TR,它是对类型T的引用,尝试创建类型"对 cv 的左值引用" TR"创建类型"对T的左值引用",同时尝试 创建类型"对 CV TR 的右值引用"创建类型 TR

[ 示例:

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&

结束示例 ]

样本中的intrintrr是完全相同的类型,即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;
}

输出:111

托马斯·贝克尔(Thomas Becker)关于右值参考文献的文章解释了一个很好的表格:

  1. A& & 成为 A&
  2. A& && 成为 A&
  3. A&& 成为 A&
  4. A&
  5. & && 成为 A&&