5

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 value than myVector.end() ?

JFMR
  • 23,265
  • 4
  • 52
  • 76
eugene
  • 39,839
  • 68
  • 255
  • 489
  • A newer question finally got an answer that, unlike all those here, _cites_ the Standard: [Is clamping on iterators valid](https://stackoverflow.com/a/62711210/2757035) – underscore_d Jul 03 '20 at 08:29

5 Answers5

6

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

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • 2
    Michiel, you aren't imaginative enough! Here's a few more options: http://stackoverflow.com/questions/1553382/pod-freeing-memory-is-delete-equal-to-delete/1553407#1553407. `:)` – sbi May 10 '11 at 08:46
2

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

Xeo
  • 129,499
  • 52
  • 291
  • 397
2

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

Nawaz
  • 353,942
  • 115
  • 666
  • 851
1

The result is undefined by the C++ Standard.

0

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).

eci
  • 2,294
  • 20
  • 18