c++iterator

Why is STL common_iterator's `operator*()` method not always const qualified?


In libstdc++ there is the following code:

  class common_iterator
  {
...
    [[nodiscard]]
    constexpr decltype(auto)
    operator*()
    {
      __glibcxx_assert(_M_index == 0);
      return *_M_it;
    }

    [[nodiscard]]
    constexpr decltype(auto)
    operator*() const requires __detail::__dereferenceable<const _It>
    {
      __glibcxx_assert(_M_index == 0);
      return *_M_it;
    }
...
}

I am trying to understand why we don't just have one operator*() const member. When I have a const reference to an iterator (not const_iterator) I think it is natural to allow dereferencing, yet this source suggests that sometimes I can't dereference such const references.

Why and in which cases does it makes sense to forbid dereferencing?


Solution

  • common_iterator can take output_iterator, and the operator*() of output_iterator is usually not const-qualified, such as back_insert_iterator.