简体   繁体   English

为什么C ++ STL向量不会超出范围

[英]Why C++ STL vector does not go out of range

I have this code and I am wondering how it works; 我有这段代码,我想知道它是如何工作的。 Why does it allow me to access an element using a value larger than the size of the vector using the operator[] ? 为什么它允许我使用operator[]使用大于向量大小的值访问元素?

But then when I use the at() function which does bounds checking, it throws the proper error. 但是,当我使用执行边界检查的at()函数时,它将引发适当的错误。

I read that the behavior of doing this is undefined , but I am curious: Why does operator[] work for out of range element access? 我读到这样做的行为是undefined ,但是我很好奇:为什么operator[]用于超出范围的元素访问?

// vector of length 3
std::vector<int> adj(3);

// output: 3
printf("Size of adj is %lu\n", adj.size());

// assign using index that is larger than vector size, e.g., 12
adj[12] = 314159;

// succeeds, output: 314159
printf("adj[12] is %d", adj[12]);

// fails, throws out_of_range
adj.at(12);

The out of bounds is not checked for speed reasons. 出于速度原因,不会检查越界。 It is assumed that the programmer knows he is in bounds before using operator[]. 假定程序员在使用operator []之前就知道自己已处于极限。

Also undefined behavior can cause anything to happed from the expected behavior, to a crash to a portal to hell opening up in you nasal cavity. 同样,未定义的行为也可能导致任何事情从预期的行为发生变化,甚至崩溃,甚至导致您的鼻腔开口进入地狱。

This is by design, indeed: the subscription operator ( operator[] ) do not check if you try to go out of bounds. 实际上,这是设计使然:订阅运算符( operator[] )不会检查您是否尝试越界。

The reason is performance. 原因是性能。 Using operator[] is as fast as accessing an element in a array. 使用operator[]与访问数组中的元素一样快。 C++ is designed around performance so this is a critically needed feature for most C++ projects in high performance domains. C ++是围绕性能而设计的,因此对于高性能域中的大多数C ++项目而言,这是至关重要的功能。

The at function is provided for projects that are ok to trade performance for runtime validation. 为可以在运行时验证中牺牲性能的项目提供了at函数。 If you don't have a critical update loop going through your vector that must be fast, and you want your code to throw if the user does ask to access data out of bound, then using at() is helpful. 如果没有遍历向量的关键更新循环,该循环必须很快,并且如果用户确实要求访问数据时希望让代码抛出,那么使用at()会很有帮助。

Most C++ users will go with operator[] by default for efficiency and make sure that no invalid index will be produced (not necessarilly by checking but simply by making the algorithm impossible to go out of bound, like by only using valid iterators and size() ) 默认情况下,大多数C ++用户都会使用operator[]来提高效率,并确保不会产生无效索引(通过检查不是必须的,而只是通过使算法不可能越界就可以了,就像仅使用有效的迭代器和size()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM