为什么在std :: vector中使用运算符[]且索引超出范围时,为什么没有异常? [英] Why I don't get an exception when using operator [] with index out of range in std::vector?

查看:108
本文介绍了为什么在std :: vector中使用运算符[]且索引超出范围时,为什么没有异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么当我使用下面的代码时,不会出现超出范围的异常?

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


推荐答案

通过使用 operator [] 您实际上是在告诉编译器我知道我在做什么。相信我。如果您访问数组之外​​的某个元素,那是您的错。您违反了这种信任;您不知道自己在做什么。

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.

另一种方法是使用 at()方法。在这里,您要求编译器对您的访问进行完整性检查。如果它们超出范围,您将遇到异常。

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.

制作 operator [] 的原因之所以不执行检查,是因为 [] 正是这样处理原始数组和指针的。 C / C ++中没有用于检查原始数组/指针的健全性检查。负担由您来检查是否必要。

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.

这篇关于为什么在std :: vector中使用运算符[]且索引超出范围时,为什么没有异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆