为什么std :: iterator没有定义const_reference和const_pointer?

时间:2014-05-29 21:18:46

标签: c++ c++11 iterator

所以,我制作了自己的符合标准的#34;容器。我定义了名为iteratorconst_iterator的嵌套类,它们派生自

std::iterator<std::bidirectional_iterator_tag, value_type>

其中value_type是我的新容器类中的typedef。我派生于std::iterator,以便我可以轻松完成

typedef typename std::iterator<std::bidirectional_iterator_tag,value_type>::value_type value_type;
typedef typename std::iterator<std::bidirectional_iterator_tag,value_type>::difference_type difference_type;
// ... etcetera

在我的嵌套迭代器类中。但是,cppreference.com说std::iterator没有针对const_reference的typedef,也没有针对const_pointer的typedef。我可以自己输入dede,但我很困惑为什么这些typedef被省略。

1 个答案:

答案 0 :(得分:5)

我刚刚审核了规范。 const_pointer仅被定义为分配器类型std::allocatorstd::allocator_traits和容器类型的一部分,并且与迭代器无关。因此,std::iterator没有定义const_pointer typedef。

是有道理的

当你考虑它时,这是有道理的,因为指向的值的常量是由迭代器本身的类型推断的。在容器中,iterator始终引用可变值,而const_iterator始终引用const值,因此不需要const_pointer typedef。

由于const_iterator的概念稍有混淆,我们可以快速查看const。要带走的关键是const iteratorconst_iterator 非常不同的东西,是的,有const const_iterator个。

 a regular iterator models these two concepts
 int*; //changable pointer, to a changable int.  Modeled by iterator.
 int* const; //constant pointer, to a changable int.  Modeled by const iterator.
 //note that iterator doesn't ever refer to `const int`.

 a const_iterator models these two concepts
 const int*; //changable pointer to constant int. Modeled by const_iterator
 const int* const; //constant pointer to constnat int. Modeled by const const_iterator.
 //note that const_iterator ALWAYS refers to `const int`.
相关问题