Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is &*vector::end() undefined behavior?

Tags:

c++

iterator

I thought &*vector::end() was undefined behavior... until I saw some post refer to Stroustrup's code:

void vector_pointer_test(element_t* first, element_t* last, int number_of_times) 
{ 
       vector<element_t> container(first, last); 
       // &*container.begin() gets us a pointer to the first element 
       sort(&*container.begin(), &*container.end()); 
       unique(&*container.begin(), &*container.end()); 
}

Is dereferencing an end() iterator undefined behavior, or is it valid?

like image 823
user541686 Avatar asked Aug 01 '12 02:08

user541686


1 Answers

It's not necessarily undefined behavior, but it depends on the specific implementation of the iterator:

C++03 24.1/5 Iterator requirements

Just as a regular pointer to an array guarantees that there is a pointer value pointing past the last element of the array, so for any iterator type there is an iterator value that points past the last element of a corresponding container. These values are called past-the-end values. Values of an iterator i for which the expression *i is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable.

The code in question has undefined behavior if container.end() is not dereferenceable. Many times a vector's iterator will simply be a pointer - in those cases there's no undefined behavior.

like image 164
Michael Burr Avatar answered Oct 21 '22 16:10

Michael Burr