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

前端 未结 5 2024
生来不讨喜
生来不讨喜 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 02:58

    The result is undefined by the C++ Standard.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-13 03:05

    It's Undefined Behavior. Anything may happen. Just to name a few of the options: Nothing at all, program exits, exception, crash.

    0 讨论(0)
  • 2021-01-13 03:20

    That would invoke undefined behaviour according to the C++ Standard (2003).

    0 讨论(0)
  • 2021-01-13 03:21

    It's undefined behaviour, the standard says nothing about the result of that.

    0 讨论(0)
提交回复
热议问题