Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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]<<"
";
  cout<<"size of a is "<<a.size()<<"
";
  return 0;
}

The result of running this code is

a[10]=10
size of a is 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
823 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

...although I can access a[10] successfully...

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.

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...