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";
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.