Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Safety: Strong Guarantee vs Basic Guarantee

Tags:

c++

exception

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?

like image 422
Pierre Avatar asked Jun 27 '26 03:06

Pierre


1 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.

like image 105
John Zwinck Avatar answered Jun 29 '26 17:06

John Zwinck