16

通过亚伯拉罕,我们有 3 种异常类型:

  1. 不扔
  2. 基本异常保证
  3. 强大的异常保证

基本意味着(如果我错了,请纠正我)保留不变量,例如保留组件的不变量,并且没有资源泄漏,其中强表示操作已成功完成或抛出异常,离开程序状态和手术开始前一模一样。

  1. 保留不变量是什么意思?如果我的一个变量中有一个有效值,那么它不会(例如指针)持有一个NULL

  2. 提到强异常保证,这是否意味着我的所有变量都会在引发异常之前存储完全相同的值?

例如 :

int main()

{
    int j = 1;
    int *p = &j;

    // do some stuff
    j = 2;
    throw 1;

}

那么在我投掷之后,j会持有价值2还是1

问候

4

2 回答 2

16
  1. Basic guarantee: after an exception was thrown, objects are left in a consistent, usable state. No resources are leaked and invariants are preserved. The state of an object might have changed, but it is still usable. For example, a date object whose day value has become -1 is not usable anymore, as its invariants say that day is in range [1, 31].

  2. Strong guarantee (additional to 1): a date object has value 2012-12-31. After an operation that tries to modify that value has failed, the value of that object is still 2012-12-31. Maybe some internal state has changed, but the logical state from the client point of view is unchanged.

于 2012-08-27T07:22:07.693 回答
5

In your case, there is NO exception guarantee. (This is basically case 0). The Wikipedia article you quoted is clear: "The rules apply to class implementations". Furthermore, after you throw, the variable j is out of scope and no longer exists. You can't even talk about its address anymore, let alone the value

Usually, class invariants are defined by the class author, so it means whatever the class author means. I don't understand your point 1. NULL is a valid value for a pointer.

Your second point is a good one. The definition isn't absolute. For instance, an operation on a string data member may increase its capacity. You can observe this on the outside via a const&. Yet, that string capacity usually is not considered as part of the string value, and therefore not as part of the class invariant.

于 2012-08-27T07:19:10.443 回答