为什么我可以有一个 constpair<const T, T> 对pair<T, T> 的引用?

phi*_*inz 6 c++ reference const-correctness

我偶然发现我可以const std::pair<const int, int>&参考std::pair<int,int>:

#include <utility>
int main()
{
    std::pair<int, int> p{1,2};
    const std::pair<const int, int>& ref_ok{p}; // why does this work?
    std::pair<const int, int>& ref_invalid{p}; // then why does this not work?
}
Run Code Online (Sandbox Code Playgroud)

考虑到const std::pair<const int, int>和std::pair<int, int>是不通过继承相关的不同类型,为什么这是可能的?

Fra*_*eux 11

const std::pair<const int, int>& ref_ok{p};实际上是具体化一个std::pair<const int, int>初始化为与引用相同的值的临时变量p,并且引用初始化是将临时变量的生命周期延长到引用的生命周期。

std::pair<const int, int>& ref_invalid{p};不允许,因为非const引用不能绑定到临时对象。

以下代码示例显示ref_ok实际上并不是对 的引用p。更改p对 没有影响ref_ok。

#include <iostream>
#include <utility>

int main()
{
    std::pair<int,int> p{1,2};
    const std::pair<const int, int>& ref_ok{p}; // why does this work?

    std::cout << p.first << ' ' << ref_ok.first << '\n';

    p.first = 5;

    std::cout << p.first << ' ' << ref_ok.first << '\n';
}
Run Code Online (Sandbox Code Playgroud)

输出 :

1 1
5 1
Run Code Online (Sandbox Code Playgroud)

实例: https: //godbolt.org/z/8bfM7fYbx