现在的位置: 首页 > 综合 > 正文

Thinking In C++笔记(一)

2012年05月02日 ⁄ 综合 ⁄ 共 2370字 ⁄ 字号 评论关闭
 

If you don't know what exceptions might occur, don't use exception specification.

Exception specification are mainly for non-template classes. Due to you don't know what will occur when template class constructor throw an exception, you program would terminate.

It is better to seperate two actions into tow seperate member function, which is exactly what the standard stack class does.     (Cohesion : every function should do one thing well!)

Operator = should adhere to the following pattern:

1.  Make sure you’re not assigning to self. If you are, go to step 6. (This is strictly an optimization.)

2.  Allocate new memory required by pointer data members.

3.  Copy data from the old memory to the new.

4.  Delete the old memory.

5.  Update the object’s state by assigning the new heap pointers to the pointer data members.

6.  Return  *this .

 A good technique is to move steps 2 and 3 into a separate function, often called clone()

Don't let destructors throw exceptions

The best advice for deciding when to use exceptions is to throw exceptions only when a function fails to meet its specification.

Don't throw exceptions from interrupt handlers.

使用异常劝诫:

1、 不要在异步机制中throw exception,尤其是中断时

2、 异常不是建立机器级别,不会处理除0终端,异常是独立于程序几倍的

3、 不要把异常作为switch等常规语句使用,效率太慢了,并且容易导致混乱

4、 如果程序简单,申请内存失败,读写错误,不要抛出异常,给出消息退出即可,不要抓住所有异常,基础地,不在必要时,不要使用异常。

5、 为什么C++标准库中没有异常规则说明,在旧代码中编写新的异常,最好把异常产生代码(try)独立出来,并编写一个异常到已有的错误消息转换handler

使用异常:

1、 确定一个问题,重复引起异常功能。

2、 修补东西,没有继续试验函数

3、 在当前上下文做任何事,抛出同一个异常到更高级上下文

4、 在当前上下文做任何事,抛出不同的异常到更高级上下文

5、 终止程序

6、 封装使用普通错误机制的函数(尤其是C库函数),使用异常代替

7、 如果错误处理机制使得事情更复杂,异常可以是错误处理更简单和有效

8、 使库和程序更安全,短期的debugging和长期的robustness

使用exception specification

  Exception specification类似函数原型,但抛出一个unexpected exception时,调用unexpected()函数,因此最好自己写一个unexpected函数,创建日志消息,然后再抛出异常或终止程序。

1、 尽可能采用标准库中的异常,如果没有,从标准库中派生,这样其他人可以调用exception类中what函数

2、 如果创建自己的异常类,最好把类嵌入到类中或名字空间中,产生一个消息,避免污染全局名字空间。

3、 使用类继承的异常,这样在自己的异常处理中只需捕获基础类类型就可以处理异常。

4、 多重继承

Catch引用,而不是值,避免:

 1、避免不必要异常对象拷贝

 2、避免对象slicing,异常类对象派生。

构造函数无返回值

1、 设置一个非局部标识,用户检测处理

2、 返回一个不完全创建的对象,用户检测。

在构造失败后继续执行类对象是非常危险的,因此构造函数是抛出异常的其中一个重要位置。需要注意的是构造抛出异常时清理资源。

如果需要在析构函数中进行异常处理,必须要在析构函数中包含try块并且在析构函数中处理所有的异常。

异常是运行时的开销,由于异常出现是rarely,因此,对于这些开销是值的,with no impacton on execution speed. 

 

Activation record instance (ARI) ------- stack frame -------

A typical stack frame contains the address of the calling function (so execution can return to it)., a pointer to the ARI of the function's static parent.

 

抱歉!评论已关闭.