Exception Safety: Strong Guarantee vs Basic Guarantee

Viewed 391

I'm trying to learn C++ right now and have gotten on the topic of exception safety. I'm pretty sure I understand the meaning of the four different levels of exception safety. However what are some concrete examples of when a strong guarantee would be inappropriate but a basic guarantee would be appropriate?

2 Answers

The strong exception guarantee is of course nice to have, and in the absence of any other consideration should be provided.

However, there are cases where providing the strong exception guarantee is too expensive, too complicated, or even impossible. Here are some examples:

  • Sorting. If a sort predicate fails, do you really want to have the logic and storage to restore the original ordering? Most use cases would not need that.
  • State changes are captured in an immutable append-only log or journal. Perhaps you can write a record saying "Cancel this action" but you cannot delete what has been written.
  • Memory has been reallocated and data has been moved. It may be pointless to move the data back to its original location. For example if a container is resized, existing data is moved, then appending a new record fails, it would probably be a waste of time to resize it to the previous size, easier to keep the new larger capacity even if the size didn't change.

In all these cases, the basic exception guarantee is still useful, and may be more appropriate. It may allow the program to continue in a valid state, e.g. by returning an error message to the user.

For example, it might be some kind of merge algorithm which is often used by sorting algorithms as well.

Scott Meyers says about basic guarantee

Some functions assure callers that even if an exception is thrown, program invariant stay intact (no data structures are corrupted ) and no resources are leaked.

So, the invariant term is important here, that's why I've decided to put extra five cents.

Also, it's worth to mention that invariant could be related to the class as the whole thing which must be consitent of course not after each statement, but at least at some key points of processing and calculating data. There can be special methods which checks out is it an invariant.

From what I undestand a strong guarantee,is like if we make a snapshot of the memory, it should be as before, probably, rarely used in user-space applications and also there should not be any side effects.

Related