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

北战南征 提交于 2019-12-30 04:53:05

问题


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";
}

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/12896773/why-i-dont-get-an-exception-when-using-operator-with-index-out-of-range-in-s

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!