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.

时间: 2024-08-25 00:05:10

STL之Errors and Exceptions的相关文章

Python Tutorial 学习(八)--Errors and Exceptions

8. Errors and Exceptions 错误与异常 此前,我们还没有开始着眼于错误信息.不过如果你是一路跟着例程走过来的,你就会发现一下错误信息.在Python里面至少有两类错误:语法错误和异常(syntax errors and exceptions) 8.1. Syntax Errors 语法错误 语法错误就是语法错误,语法错误就是语法错误. 比如说,关键词拼写错误,缩进错误,标点符号错误等等,比如下面这个栗子里面的在while循环的时候漏写了冒号引起的语法错误,注意错误提示中意既

16 Errors and Exceptions

System.IO.IOException System.ComponentModel.Composition.CompositionException System.Exception System.SystemException:运行时抛出 System.ApplicationException:使用已经背离了设计的初衷 System.StackOverflowException System.IO.EndOfStreamException System.OverflowException

Python Errors and Exceptions

1. python中的try{}catch{} 2. raise exception 3. try...except ... else.. 4. finally块 python中的异常处理的keyword和c#中的是不同样的,python中使用try,except关键在来处理异常,例如以下: 2. raise excepption python中假设在except中假设须要将异常又一次抛出能够使用keywordraise,类似于c#中的throwkeyword. It is useful for

ruby Errors &amp; Exceptions

When you first started coding, errors were probably the last thing you wanted to see. After all, it’s not a far stretch to associate “error” with “I messed up”. Hopefully by now you’ve come to appreciate the value of a good error message. Take a look

Checked exceptions: Java’s biggest mistake-检查型异常:Java最大的错误(翻译)

原文地址:http://literatejava.com/exceptions/checked-exceptions-javas-biggest-mistake/ 仅供参考,毕竟我四级都没过 Checked exceptions have always been a controversial feature of the Java language. 检查型异常一直是Java语言当中有争议的特性 Advocates claim they ensure checking & recovery f

java 断言

面试的时候遇到了一个什么时候才使用assert的问题----断言 当时懵了,不知道如何回答,结果面试官也说assert----断言在c语言中使用的可能比较多,java的话除非学的比较深,不然一 般不会了解到.委婉的给了基础不扎实的我一个台阶下吧.首先来看看java的api文档,来看看java.lang.Throwable类. The Throwable class is the superclass of all errors and exceptions in the Java languag

python requests学习

1.无参数直接get >>> import requests >>> r = requests.get("http://httpbin.org/get") >>> r.status_code 200 >>> print(r.text) { "args": {}, "headers": { "Accept": "*/*", "A

java命令行

Launches a Java application. Synopsis java [options] classname [args] java [options] -jar filename [args] javaw [options] classname [args] javaw [options] -jar filename [args] options Command-line options separated by spaces. See Options. classname T

Pyhon 嵌入C/C++模块(一)

1 Extending Python with C or C++ It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can’t be done directly in Python: they can implement new built-in object types, an