Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I don't get an exception when using operator [] with index out of range in std::vector?

Tags:

c++

stl

Why when I use below code I don't get an out of range exception ?

std::vector<int> v;
v.resize(12);
int t;
try {
    t = v[12];
} catch(std::exception  e){
    std::cout<<"error:"<<e.what()<<"\n";
}
like image 639
herzl shemuelian Avatar asked Oct 15 '12 13:10

herzl shemuelian


2 Answers

By using operator[] you are essentially telling the compiler "I know what I'm doing. Trust me." If you access some element that is outside of the array it's your fault. You violated that trust; you didn't know what you were doing.

The alternative is to use the at() method. Here you are asking the compiler to do a sanity check on your accesses. If they're out of bounds you get an exception.

This sanity checking can be expensive, particularly if it is done in some deeply nested loop. There's no reason for those sanity checks if you know that the indices will always be in bounds. It's nice to have an interface that doesn't do those sanity checks.

The reason for making operator[] be the one that doesn't perform the checks is because this is exactly how [] works for raw arrays and pointers. There is no sanity check in C/C++ for accessing raw arrays/pointers. The burden is on you to do that checking if it is needed.

like image 60
David Hammen Avatar answered Oct 27 '22 01:10

David Hammen


operator[] doesn't throw an exception. Use the at() function for that behaviour.

like image 39
chris Avatar answered Oct 27 '22 01:10

chris