这个const引用std :: pair如何工作?

joh*_*een 2 c++ stl const std-pair

考虑std::mapSTL中的类:

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;
Run Code Online (Sandbox Code Playgroud)

迭代器std::map返回类型的对象

std::pair<const key_type, T>
Run Code Online (Sandbox Code Playgroud)

这里要注意的重要一点是,该对中的第一个成员是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
Run Code Online (Sandbox Code Playgroud)

但是,以下表达式有效

const std::pair<key_type, T>& reference = *map_iterator;  // Correct, const reference is okay
Run Code Online (Sandbox Code Playgroud)

因此,通过某种机制,std::pair<const key_type, T>可以通过引用type引用type的对象const std::pair<key_type, T>。这在逻辑上是合乎需要的(因为成员和conststd::pair隐含const性都与兼容)。firstsecondstd::pair<const key_type, T>

但是,我有兴趣知道哪种C ++实现机制可以实现这种兼容性。我确定有实现上述两种引用类型不兼容的std :: pair的方法。

Nat*_*ica 6

当你做

const std::pair<key_type, T>& reference = *map_iterator;
Run Code Online (Sandbox Code Playgroud)

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

std::pair<key_type, T> copy = *map_iterator; 
Run Code Online (Sandbox Code Playgroud)

The above conversion sequence works because you are allowed up to one user defined conversion in initialization and the compiler will try to do that to give you a valid initialization.