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

后端 未结 2 1694
梦毁少年i
梦毁少年i 2021-02-07 14:15

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

void vector_pointer_test(element_t* first         


        
2条回答
  •  不知归路
    2021-02-07 14:57

    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.

提交回复
热议问题