Are vectors more stringent when checking bounds than heap arrays?

How stringent are the bounds on vector boundaries compared to heap arrays? How exactly does it check boundaries and how does this compare with how the heap array is checked?

+6
c ++ arrays vector
source share
3 answers

A vector will check for border checks if you use the at() function, for example:

 std::vector<int> v(5); v.at(3) = 10; v.at(5) = 20; // throws an exception, std::out_of_range 

However, if you use operator[] , border checking is not performed. (And access to non-existent elements leads to undefined behavior.)

It should be noted, however, that most implementations will be able to include border checking on all iterators, which is discussed in the answers here . By default, VS2008 and below are included in Debug and Release, VS2010 only works in Debug. gcc requires that you define _GLIBCXX_DEBUG to get validated iterators.

+17
source share

This will be implemented as an implementation, the vector contract does not give any guarantees of binding verification. But you know for sure that it will be no worse than an array of heaps.

In my sgi implementation:

  • vector::operator[] not checked
  • vector::at() tied to validation

From the definition of the header file operator[] :

  /** * @brief Subscript access to the data contained in the %vector. * @param n The index of the element for which data should be * accessed. * @return Read-only (constant) reference to data. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ 

And for vector::at() :

  /** * @brief Provides access to the data contained in the %vector. * @param n The index of the element for which data should be * accessed. * @return Read/write reference to data. * @throw std::out_of_range If @an is an invalid index. * * This function provides for safer data access. The parameter * is first checked that it is in the range of the vector. The * function throws out_of_range if the check fails. */ 
+1
source share

In a typical implementation, arrays are not checked at all, regardless of distribution. std::vector requires border checking on at() . Accessing borders using operator[] gives undefined behavior, so you can also check borders on it, but this is rather unusual.

More importantly, however, I would suggest that you generally use algorithms that basically fix the problem in the first place. When you do something like: for (i=0; i<N; i++) , it is pretty easy for N to be wrong. When you use algorithm(x.begin(), x.end(), ...); It’s much easier to get a reasonable degree of confidence in the correctness of your logic.

+1
source share

All Articles