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

后端 未结 2 1643
梦毁少年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:50

    It's undefined behaviour. That is, behaviour not defined by the C++ standard. It may be defined by the implementation. More likely, it will happen to work by chance in some situations and not others.

    In this case, if the iterator is a raw pointer the compiler will likely optimise &*i into a no-op, so it will likely work. Stroustrup may have known his vector used raw pointers as iterators.

    Even if the compiler doesn't optimise it away, in practice, it's only likely to fail if the vector's memory happens to be allocated to end at a segment boundary. (Or if the iterator implementation is written to check for being non-dereferenceable, eg for debugging purposes.)

    In C++11 this should be written as:

    sort(container.data(), container.data()+container.size()); 
    

提交回复
热议问题