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

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.


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

Tags:

C++

Stl