Hawk_Y
Hawk_Y

Reputation: 5

understanding the type of dereference - const_iterator

I have this declaration:

list<string*>::const_iterator iter;

I am trying to understand whether the type of *iter is: string* , const string* or something else.

I read that cost_iterator returns reference. On the one hand the list contains string* and the iterator points to those. on the other hand it is const_iterator so the value it points to should be const and it acts as if the data in the list is const? despite it is not really? not sure what am I missing and what is the right answer.

Upvotes: 0

Views: 454

Answers (2)

Useless
Useless

Reputation: 67723

The general answer is const T &, which I prefer to write T const & because it composes correctly in the next paragraph.

For T=string*, we get string * const &, or a reference to a constant pointer to a string.

This means you can't mutate the list element (via a const_iterator) by pointing it to a different string, but you can indirectly mutate the list by altering the string to which it points.

You can read the definitions of std::list<T>, but it isn't as clear as it could be about the iterator behaviour - it works out like so:

  • std::list<T>::value_type is the same as T

    • so std::list<string*>::value_type is string*.
  • std::list<T>::const_iterator models a const LegacyBidirectionalIterator

  • LegacyBidirectionalIterator is a LegacyForwardIterator which must satisfy LegacyInputIterator

  • LegacyInputIterator must support the expression *i returning type reference

  • and finally, from the LegacyForwardIterator we rather skipped over

    • The type std::iterator_traits::reference must be exactly

      ... const T& otherwise (It is constant),

    (where T is the type denoted by std::iterator_traits::value_type)

    which is how we get from the type named reference to the const T & we started with.

Upvotes: 3

NathanOliver
NathanOliver

Reputation: 180500

std::list<T>::const_iterator::operator* returns a const T&. Since your list stores a string* that means you'll get a reference to a string * const as the const applies to T, not to what T points to if it is a pointer.

Upvotes: 5

Related Questions