What is an iterator's default value?

前端 未结 4 712
你的背包
你的背包 2020-11-28 13:20

For any STL container that I\'m using, if I declare an iterator (of this particular container type) using the iterator\'s default constructor, what will the iterator be init

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 13:45

    An updated answer.

    Up to and including C++11: a default- and value-initialized iterator may contain a singular value. Technically it may not be compared, nor dereferenced. See [iterator.requirements.general]/p5.

    By convention however, STL implementations used to initialize such an iterator as a past-the-end iterator.

    Starting from C++14: a value-initialized forward iterator compares equal to a past-the-end iterator. See [iterators.forward.iterators]/p2:

    ... value-initialized iterators may be compared and shall compare equal to other value-initialized iterators of the same type. [ Note: Value-initialized iterators behave as if they refer past the end of the same empty sequence.  — end note ]

    Therefore:

    std::list::iterator iter {}; should work as a past-the-end iterator.

    std::list::iterator iter; is dangerous as iter will be initialized only if one has a non-trivial default constructor. Though for std::list that will probably be the case, and so should also work.

提交回复
热议问题