Is this example code valid?
#include<vector>
using namespace std;
int main() {
vector<int> vec(10); // create with 10 elements
vec.reserve(100); // set capacity to 100
vector<int>::iterator iter = vec.end(); // points 1 past vec[9]
vec.push_back( 777 );
bool is_this_valid_and_true = *iter == vec[10]; // ?
// VS2010 runtime error in debug build:
// Expression: vector iterator not dereferencable
// Works in release build
iter = vec.end() + 1; // points 2 past vec[10]?
vec.push_back( 888 );
vec.push_back( 999 );
is_this_valid_and_true = *iter == vec[12]; // ?
}
The error in VS2010 may be related to this bug.
If I set the command line option /D_HAS_ITERATOR_DEBUGGING=0 or set
#define _HAS_ITERATOR_DEBUGGING 0
#include<vector>
there is no error.
Edit:
In light of the answers, I think this code should cause an error. There is no bug in the compiler. It only works in release mode because iterators are implemented as pointers.
You are thinking of iterators as pointers.
Iterators may use pointers as an implementation detail but they are not actual pointers.
Thus:
There is no such thing as two elements passed the end of data.
vec.end() returns an iterator that when decrement is a reference to the last elements (assuming there are elements). While an iterator referencing the last element when incremented is equivalent to the iterator returned by end().
But de-referenceing the iterator representing by end() is undefined behavior() (even if you have reserved space) (the implementation may not be using pointers. For example some of the DeBug STL implementations will do extensive error checking in the iterator code).