标准引用:对`vector :: operator []`的超出范围调用是否会调用未定义行为? [英] Standard citation: Does an out of range call to `vector::operator[]` invoke Undefined Behavior?

查看:61
本文介绍了标准引用:对`vector :: operator []`的超出范围调用是否会调用未定义行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

#include <vector>

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

我知道上面的代码调用了Undefined Behavior,因为在v[1]的调用位置,根据v.size()的向量的大小为< 1.(为零.)

I am aware that the above code invokes Undefined Behavior, because at the call-site for v[1], the size of the vector according to v.size() is < 1. (It is zero.)

但是,我花了最后一个小时左右的时间浏览C ++标准,以直接或间接地澄清这实际上是未定义的行为.

However I have spent the last hour or so looking through the C++ Standard for a citation that either directly or indirectly clarifies that this is, in fact, Undefined Behavior.

也许我错过了显而易见的事情.您能否至少从C ++ 03以及可选的C ++ 11标准中提供引用?

Maybe I have missed the obvious. Can you provide a citation or citations from at least the C++03 and optionally the C++11 Standard which clears this up?

推荐答案

这是operator[]定义方式的产物.在§23.2.3[sequence.rqmts]表101中,operator[]的操作语义定义为*(a.begin() + n).因此,它是根据迭代器定义的.根据§24.2.1/5 [iterator.requirements.general],将begin递增到end并对其取消引用是未定义的行为.

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].

这篇关于标准引用:对`vector :: operator []`的超出范围调用是否会调用未定义行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆