c++ what's the result of iterator + integer when past-end-iterator?

前端 未结 5 2025
生来不讨喜
生来不讨喜 2021-01-13 02:28

suppose you have a random access iterator (eg of std::vector myVector)

when iter + someInt is past-end-iterator, iter + someInt == my

5条回答
  •  南笙
    南笙 (楼主)
    2021-01-13 03:00

    As it is true that this leads to undefined behavior (see other answers) after the c++ standard, one is sometimes currios, what will actually happen?

    In fact, this is often not mystical at all and pretty clear what will happen, however it is dependend on the used compiler and its version and its standard library and compiler flags and your OS. This also means, that you absolutely should not depend on it (e.g. next compiler version may change behavior).

    For your question (You should not rely on the following): In current compilers (gcc,msvc,intel c++ compiler) a std::vector has usually (at least) two members:

    T* _begin_; // pointing to begin of array of vector
    T* _end_; // pointing to end(), note that array might be larger due to reserve()
    

    So usually you will just get a pointer beyond end: nothing mean happens. Often you can even dereference it easily (either because array is larger than

    _end_-_begin_
    

    or because the memory afer can be accessed by the program. Of course, the content might be rubbish).

    If you are really interested, look at the Assembler Code (with optimizations and without).

提交回复
热议问题