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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With