Standard citation: Does an out of range call to `vector::operator[]` invoke Undefined Behavior?

后端 未结 3 555
礼貌的吻别
礼貌的吻别 2021-01-21 19:49

Consider:

#include 

int main()
{
  std::vector  v;
  v.reserve (100);
  v[1] = 42;
}

I am aware that the above code i

3条回答
  •  自闭症患者
    2021-01-21 20:23

    This doesn't answer your underlying question, but your vector isn't of size 0, it is of size 100 (since you created it with the size constructor)

    The man page for std::vector does claim it's undefined behaviour, but I don't know if you consider that to be "good enough" (you asked for a citation from the c++ standard)

    template> reference std::vector< _Tp, _Alloc >::operator[] (size_type__n)
       [inline]
       Subscript access to the data contained in the vector. Parameters:
           n The index of the element for which data should be accessed.
    
       Returns:
           Read/write reference to data.
    
       This operator allows for easy, array-style, data access. Note that data access with this operator is unchecked and
       out_of_range lookups are not defined. (For checked lookups see at().)
    
       Definition at line 695 of file stl_vector.h.
    

提交回复
热议问题