Decrease begin () of the iterator and then increase it again

Are such statements valid by standard?

std::string str{"123"}; auto it = str.begin(); --it; ++it; // Does *it point to character '1' now? 

I tried this on g ++ 4.7.2 and clang ++ 3.5 - *it returns '1' . Is this the standard behavior in C ++ 11?

+7
c ++ c ++ 11
source share
1 answer

No, this is not true.

This behavior is undefined since 24.2.6 [bidirectional.iterators] states that the --it is that the result should be dereferenced. Since it points before begin() in your example, this condition is not fulfilled and, therefore, the code is illegal.

Since there is no need for diagnosis, this may seem to have worked, but you cannot (and should not) rely on it.

+13
source share

All Articles