std::pair 的常量引用如何工作?

How does this const reference for std::pair work?

考虑 std::map class 在 STL 中:

template < class Key,                                     // map::key_type
           class T,                                       // map::mapped_type
           class Compare = less<Key>,                     // map::key_compare
           class Alloc = allocator<pair<const Key,T> >    // map::allocator_type
           > class map;

std::map return 类型

对象的迭代器
std::pair<const key_type, T>

这里要注意的重要一点是,这对中的第一个成员是 const。这意味着,下面的引用赋值是无效的.

std::pair<key_type, T>& reference = *map_iterator;        // Incorrect, key_type is not const

std::pair<const key_type, T>& reference = *map_iterator;  // Correct

但是,下面的表达式是有效的

const std::pair<key_type, T>& reference = *map_iterator;  // Correct, const reference is okay

因此,通过某种机制,std::pair<const key_type, T> 类型的对象可以通过 const std::pair<key_type, T> 类型的引用来引用。这在逻辑上是可取的(因为 constness of std::pair 隐含了成员 firstsecondconstness,这与 std::pair<const key_type, T> 兼容).

但是,我很想知道是什么 C++ 实现机制使这种兼容性成为可能。我敢肯定,在上述两种引用类型不兼容的情况下,有实现 std::pair 的方法。

当你这样做时

const std::pair<key_type, T>& reference = *map_iterator;

*map_iteratorreturns一个std::pair<const key_type, T>&。然后从中复制初始化一个 std::pair<key_type, T>,然后将 reference 绑定到该临时变量。因为您有对 const 的引用,这会将临时对象的生命周期延长为引用的生命周期,并且您现在拥有一个元素,该元素是地图中元素的副本。基本上你已经完成了

std::pair<key_type, T> copy = *map_iterator; 

上述转换序列之所以有效,是因为您在初始化中最多允许进行一次用户定义的转换,编译器将尝试这样做以提供有效的初始化。