0

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.

1
  • 1
    Type should be string const * - `constant pointer to non const data Commented Aug 20, 2019 at 20:06

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That question looked familiar: stackoverflow.com/questions/309581/…
3

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.

1 Comment

Well put. My Stroustrup 4ed says " const_iterator Behaves like a const value_type "

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.