Are non dereferenced iterators past the “one past-the-end” iterator of an array undefined behavior?

后端 未结 4 1424
醉话见心
醉话见心 2020-12-03 08:06

Given int foo[] = {0, 1, 2, 3}; I want to know if iterators that point past the \"one past-the-end\" are invalid. For example: auto bar = cend(foo) + 1;

4条回答
  •  悲&欢浪女
    2020-12-03 08:50

    TL;DR -- It is undefined behavior to compute an iterator past the one-past-the-end iterator because a precondition is violated in the process.


    Lightness provided the quote that authoritatively covers pointers.

    For iterators, incrementing past the "end" (one-past-the-last-element) is not prohibited generally, but it IS prohibited for most of the various kinds of iterators:

    The input iterator requirements, and the only incrementable if dereferenceable clause in particular, are incorporated by reference into forward, bidirectional, and random-access iterators.

    Output iterators are not so constrained, they are always incrementable. Because there is no end, iterators past-the-one-past-the-end are excluded by definition, so worrying about whether they would be legal to compute is moot.

    Then, jumping forward in the sequence is defined in terms of individual incrementation, so we conclude that computation of a past-the-one-past-the-end iterator is either meaningless or illegal for all iterator types.

提交回复
热议问题