首页 > 代码库 > STL之Errors and Exceptions
STL之Errors and Exceptions
Error Handling
STL设计的目标是性能最优化,而不是最安全。
错误检查是极其浪费时间的,因此,STL对于错误处理几乎没有做处理,因此,这对STL的使用者的要求就非常高。
为什么不采取错误处理呢,下面是两个主要原因:
- Error checking reduces performance, and speed is still a general goal of programs. As mentioned, good performance was one of the design goals of the STL.
- If you prefer safety over speed, you can still get it, either by adding wrappers or by using special versions of the STL. But you can‘t program to avoid error checking to get better performance when error checking is built into all basic operations. For example, when every subscript operation checks whether a range is valid, you can‘t write your own subscripts without checking. However, it is possible the other way around.
Pay Attention
要不出错地使用STL,下面几点是必须满足的:
Iterators must be valid. For example, they must be initialized before they are used. Note that iterators may become invalid as a side effect of other operations. In particular, they become invalid for vectors and deques if elements are inserted or deleted, or reallocation takes place.
Iterators that refer to the past-the-end position(结束之后的位置) have no element to which to refer. Thus, calling operator * or operator -> is not allowed. This is especially true for the return values of the end() and rend() container member functions.
Ranges must be valid:
Both iterators that specify a range must refer to the same container.
The second iterator must be reachable from the first iterator.
If more than one source range is used, the second and later ranges must have at least as many elements as the first one.
Destination ranges must have enough elements that can be overwritten; otherwise, insert iterators must be used.
possible errors
// stl/iterbug1.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> coll1; //empty collection vector<int> coll2; //empty collection /* RUNTIME ERROR: * - beginning is behind the end of the range */ vector<int>::iterator pos = coll1.begin(); reverse (++pos, coll1 .end()); //insert elements from 1 to 9 into coll2 for (int i=1; i<=9; ++i) { coll2.push_back (i); } /*RUNTIME ERROR: * - overwriting nonexisting elements */ copy (coll2.begin(), coll2.end(), //source coll1 .begin()) ; //destination /* RUNTIME ERROR: * - collections mistaken * - begin() and end() mistaken */ copy (coll1.begin(), coll2.end(), //source coll1. end()); //destination }
Note that these errors occur at runtime, not at compile time, and thus they cause undefined behavior.
STL之Errors and Exceptions