GotW # 82 Exception Safety and Exception Specifications: Is it worth it?

xiaoxiao2021-03-06  42

GotW # 82 Exception Safety and Exception Specifications: Is it worth it?

Original article See: www.gotw.ca/gotw/082.htm

Difficult: 8/10

Is it worthwover about the code for unusual security? Write an abnormal specification? You may be surprised that these problems are still controversial and arguing, and even an expert, the opinions are not as good.

problem

JG problem:

1. Old words Rehabilitation: The definition of the Abrahams Exception Safety Guarantees (Basic Guarantee, Strong Guarantee, No Throwing Guarantee).

2. What happens if the violation of an abnormal specification? why? Discusses the basic principles of C this characteristics.

Guru problem:

3. When is it worth writing code that meets the following requirements:

a) Basic guarantee? b) strong guarantee? c) No throwing guarantee?

4. When is it worth writing an exception specification for a function? Will you write? Give your reason.

answer

1. Basic guarantee means that allows failure to change the program state, but the object / module that cannot be leaked and failure must still be destructed and available, and the status must be reliable (but not fully predictable) ). Strong guarantee includes a transactional submission / revocation semantic: failure operation must ensure that the program status of the object of this operation is not changed. This means that the object is completely unaffected, which also includes the validity or role of the Helper object (Contents) is not affected, such as the Iterator object of Container. No throwing guarantee means that failure operations will not occur at all. This operation does not throw an exception.

2. The idea of ​​an exception specification is to do running period checks to ensure that only specific types of exceptions are thrown (or do not throw any exception at all). For example, the exception specification of the following function guarantees F () only throws an exception of A or B type:

INT f () throw (a, b);

If an exception is not in the "Visitor" list ("INVITED-Guests" List, the function UNEXPECTED () will be called. E.g:

INT f () throw (a, b)

{

Throw c (); // will call unExpected ()

}

You can use the standard set_unexpected () function to register your own processing function, which can cope with the situation of "unforesented" unforesenching. Your handlers must do not accept parameters and have no return values. E.g:

Void myunexpectedhandler () {/*...*/}

Std :: set_unexpected (& myunexpectedhandler);

What is the next question is what your UNEXPECTED handler does? One thing that it can't do is returned back to Return Via A Usual Function Return by ordinary function. And it can do two things:

1) It can convert the exception to an exception specification. It can throw an exception that meets the "Abnormal Normature List", which is this "exception specification list" causes the process being called. Next, the "Stack Expand" process will continue from the function stopped.

2) It can call terminate (). (TermnInate () function can also replace it, but it must terminate the program.)

3. Write at least one guarantee code is definitely worth it. There are several good reasons:

1) Abnormal occurrence. (To explain the popular statement.) They will definitely happen. The standard library will throw an exception. The language itself will also throw an exception. We must write some code for an exception. Fortunately, workload is not big, because we know what to do now. To this end, some habits must be cultivated, and even these habits must be followed - but also pay attention to learning programming from the wrong code.

One has always been a very difficult big problem is the error handling. How to report an error? Returns an error code or throw an exception can report an error. The details of this problem are almost entirely a detail of grammar, and their main difference is how to report errors, so each method has their own different styles.

2) Write the code to exceptionally safe to you.

The code and good code for exceptionally safe are always there. Those who help us write an exception security code is the thing we have to do anything, even more is unrelated to abnormalities. In other words, unusual security technology is beneficial to your code itself, even if it is not considered at all.

Look at the following, this is what I and other people think that this is easier to write an exception security code, think about this main technology:

l Manages the allocation of resources using "Resource Acquisition IS Initialization) (RAII). Use resource allocation objects similar to the LOCK class and Auto_PTRS is usually a good idea. In the many benefits of this, we should also find "unusual security", which is not surprising. You should often discover the function (of course, what you write here is not what you wrote, but what other functions written) Some program branches will return prematurely because of the failure of the cleanup action, the reason is that the cleaning action is not using RAII. Automated.

l "Do all work from small, then guarantees only an abnormally thrown action" to avoid changing the program internal state until you can ensure that the entire operation will succeed. Such transactional programming methods can comply more clear, cleaner, safer code, even some of them. You should also often see the function in the function (here is still the work of other people, not what you write), some program branches returned too early because of the failure of saving the status of the object, because before the operation failed, There are some small problems in the internal state of the program.

l Adherence to "a class (or function), only one task". A function of multiple functions is difficult to do, such as strongly exception-saFETY, such as "Exceptional C ", Terms 10 to 18 Stack :: Pop () and EvaluateSalaryandReturnName () functions. Many abnormal security problems can be solved more simply, or unintentionally eliminated, as long as it simply implements a function, only one task is just a strategy. This strategy is being applied to an unusual security; this is definitely a good idea, and it is natural and natural.

If you do this, you will have to benefit you.

So when should we achieve what level of guarantee? In short, there is a policy that is followed by a C standard library. You can use it to apply it to your own code:

Strategy

A function should always support the most stringent guarantee, and will not cause harm to users who do not need this guarantee.

So, if your function can support no throw assurance, it does not affect some users, then it should do without throwing assurance. It is worth noting that some key functions, such as destructors, and recycling functions, must definitely do not thrown, otherwise, it is impossible to safely and reliably perform cleaning measures.

Otherwise, if your function can support strong guarantees and do not punish some users, then it should be strong. Note that some functions such as Vector :: INSERT () are generally not doing strong guarantees, because in order to achieve strong guarantees, we must complete the content of the entire vector when you insert an element. And not all programs need to pay attention to strong guarantees, which will lead to excessive costs. (Those programs that need strong guarantees can "pack" vector :: insert (), general practices in a strong guarantee: Copy a vector, inserted in this copy, once successful and original vector SWAP () exchange). Otherwise, your function should support basic guarantees.

For more information on the above, such as: Swap () does not thrown, why the destructor should do without throw, please refer to "Exceptional C " [1] and "More Exceptional C " [2 ].

4. Simple say, don't be afraid. Even if the experts will not be troublesome.

Description White, the main problem is:

N abnormal specifications will cause surprising performance loss, for example, the compiler closes the inline characteristics of the function of the specified exception specification.

n One period of runtime is often not what you expect, the exception can be captured.

n Normally, you can't write a truly useful exception specification for the function template, because you often can't clarify the type of exception.

For more information, you can view the Basic Principles of Boost Abnormal Specification at http://www.gotw.ca/publications/xc /boost_es.htm (the content is summarized as "don't!").

references:

[1] H.sutter.Exceptional C (Addison-Wesley, 2000).

[2] H.sutter.more Exceptional C (Addison-Wesley, 2002).

转载请注明原文地址:https://www.9cbs.com/read-73748.html

New Post(0)