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

后端 未结 3 558
礼貌的吻别
礼貌的吻别 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:21

    It's an outgrowth of how operator[] is defined. In §23.2.3 [sequence.rqmts] Table 101, the Operational Semantics of operator[] is defined as *(a.begin() + n). So it's defined in terms of iterators. And incrementing begin past end and dereferencing it is undefined behavior according to §24.2.1/5 [iterator.requirements.general].

提交回复
热议问题