Why is comparing against "end()" iterator legal?

Posted by sharptooth on Stack Overflow See other posts from Stack Overflow or by sharptooth
Published on 2010-04-28T09:42:15Z Indexed on 2010/04/28 9:53 UTC
Read the original article Hit count: 225

Filed under:
|
|
|

According to C++ standard (3.7.3.2/4) using (not only dereferencing, but also copying, casting, whatever else) an invalid pointer is undefined behavior (in case of doubt also see this question). Now the typical code to traverse an STL containter looks like this:

std::vector<int> toTraverse;
//populate the vector
for( std::vector<int>::iterator it = toTraverse.begin(); it != toTraverse.end(); ++it ) {
    //process( *it );
}

std::vector::end() is an iterator onto the hypothetic element beyond the last element of the containter. There's no element there, therefore using a pointer through that iterator is undefined behavior.

Now how does the != end() work then? I mean in order to do the comparison an iterator needs to be constructed wrapping an invalid address and then that invalid address will have to be used in a comparison which again is undefined behavior. Is such comparison legal and why?

© Stack Overflow or respective owner

Related posts about c++

Related posts about stl