Only Subscript Elements that Are Known to Exist!

C++ Primer 4/e 在Iterators这里有一个警告:‘It is crucially important to understand that we may use the subscript operator, (the [] operator), to fetch only elements that actually exist. For example,

     vector<int> ivec;      // empty vector
     cout << ivec[0];       // Error: ivec has no elements!

     vector<int> ivec2(10); // vector with 10 elements
     cout << ivec[10];      // Error: ivec has elements 0...9

 

Attempting to fetch an element that doesn’t exist is a run-time error. As with most such errors, there is no assurance that the implementation will detect it. The result of executing the program is uncertain. The effect of fetching a nonexisting element is undefinedwhat happens will vary by implementation, but the program will almost surely fail in some interesting way at run time.

This caution applies any time we use a subscript, such as when subscripting a string and, as we’ll see shortly, when subscripting a built-in array.

Attempting to subscript elements that do not exist is, unfortunately, an extremely common and pernicious programming error. So-called “buffer overflow” errors are the result of subscripting elements that don’t exist. Such bugs are the most common cause of security problems in PC and other applications.’

中文版的是这样说:‘我们只能以subscript运算子([])取出实际存在的元素。这一点十分重要。例如:

    vector<int> ivec;         // 空的 vector
    cout << ivec[0];           // 错误: ivec 里没有元素
  
  vector<int> ivec2(10); // vector 内含 10 个元素
     cout << ivec[10];        // 错误: ivec 的元素编号是0到9

撷取不存在的元素会造成执行期错误。编译器并不保证能侦测出大部分此类错误。这个程式的执行结果无法确定,因为“撷取不存在元素”是一种不明确的行为,其结果视编译器而不同,但几乎可以确定会在执行期出现某种有趣的错误。

这个警告亦可套用于任何使用下标的时候,例如对string或(很快会看到)对内建的array取下标。

不幸的是,企图以下标存取不存在的元素是极常见且致命的编程错误。所谓缓冲区上限溢位(buffer overflow)错误就是以下标存取不确定元素的结果。这种臭虫是形成PC程式及其他应用程式安全问题的最常见原因。’

这个是很有用的警告,特别是从VB 微软系列到C 系列的阵列使用常会弄错元素是0开始或是1开始。