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";
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With