简体   繁体   中英

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[] ?

But then when I use the at() function which does bounds checking, it throws the proper error.

I read that the behavior of doing this is undefined , but I am curious: Why does operator[] work for out of range element access?

// 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[].

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.

The reason is performance. Using operator[] is as fast as accessing an element in a array. C++ is designed around performance so this is a critically needed feature for most C++ projects in high performance domains.

The at function is provided for projects that are ok to trade performance for runtime validation. 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.

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() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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