开发者

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

开发者 https://www.devze.com 2023-03-03 22:34 出处:网络
suppose you have a random access iterator (eg of std::vector myVector) when iter + someInt is past-end-iterator,

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

when iter + someInt is past-end-iterator, iter + someInt == myVector.end() ??

or could it be different v开发者_运维技巧alue than myVector.end() ?


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


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


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


The result is undefined by the C++ Standard.


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

精彩评论

暂无评论...
验证码 换一张
取 消