当索引超出向量类的范围时,没有编译错误或运行时错误? [英] No compilation error or run time error when index out of range of vector class?

查看:101
本文介绍了当索引超出向量类的范围时,没有编译错误或运行时错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用向量类时,我发现当索引超出向量的范围时,没有编译错误或运行时错误。该问题可以通过以下代码显示:

When I was using vector class, I found out that there is no compilation error or run time error when indexing out of range of a vector. The problem can be shown by the following code

#include <iostream>
#include <vector>

using namespace std;

int main(){

  vector<double> a(10,0.0);
  a[10]=10.0;
  cout<<"a[10]="<<a[10]<<"\n";
  cout<<"size of a is "<<a.size()<<"\n";
  return 0;
}

运行此代码的结果是

a[10]=10
size of a is 10

没有报告错误。另一个要注意的是, a.size()仍然返回 10 ,虽然我可以访问 a [10]

with no error reported. Another thing to notice is that a.size() still returns 10, although I can access a[10] successfully.

我的问题是,有没有办法让程序报告一个错误,当一个人尝试索引出一个向量的范围?

My question is that is there a way to let the program report an error when one tries to index out of the range of a vector?

推荐答案

这是设计。为了提供最佳性能, operator [] 不检查参数的有效性。与裸型数组一样,访问向量边界外的元素会导致未定义的行为

This is by design. To offer maximum performance, operator[] does not check the argument for validity. Just like with naked arrays, accessing an element outside the bounds of a vector results in undefined behaviour.


...虽然我可以访问 a [10] 成功...

这是未定义行为的允许表现形式。同样允许你的代码抛出异常,崩溃,通过你的所有测试,然后在你的客户的脸上爆炸,发动核打击等。

This is a permissible manifestation of undefined behaviour. It is equally permissible for your code to throw an exception, to crash, to pass all your tests but then blow up in your customer's face, to launch a nuclear strike etc.

您可以使用 std :: vector :: at(index) 用于边界检查访问。如果索引是,则引发 std :: out_of_range 无效。

You could use std::vector::at(index) for bounds-checked access. It throws std::out_of_range if the index is not valid.

边界检查与无边界检查不一定是全有或无关的命题:请参阅 /问题/ 1290396 /如何使make-stdvectors-operator-compile-do-bounds-checking-in-debug-but>如何使std :: vector的operator [] compile在DEBUG中执行边界检查,但不在RELEASE Valgrind 等工具。

Bounds checking vs no bounds checking does not have to be an all-or-nothing proposition: see How to make std::vector's operator[] compile doing bounds checking in DEBUG but not in RELEASE and tools like Valgrind.

这篇关于当索引超出向量类的范围时,没有编译错误或运行时错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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