Exception security has two goals:
Do not disclose any resources. This can be done by RAII.
Do not destroy data structures. This is what we're going to talk about.
There are three levels of exception security:
Basic security: Objects and data structures also have a legitimate state after an exception occurs. Implementation is simple and should be a minimum requirement.
Very safe: The program state is not changed after throwing an exception. That is, "atomic", if success is completely successful, failure will remain intact. The copy and swap strategy in this article is the means to achieve this.
Do not throw exceptions: always implement functionality, built-in types can do this.
The so-called copy and swap strategy is to first make a copy of the object that needs to be modified, the construction of this copy uses RAII to ensure that no resources are compromised, complete the required modifications on the replica, and the original object remains unchanged if an exception occurs during the modification. After the modification is complete, the copy is exchanged with the original object by Non-throwing swap.
classstring{Char*str; Public: String&operator=(ConstString &s) {String temp (s);//RAIITemp.swap (* This);//non-throwing Swap return* This; } voidSwap (String & S)Throw()//implementation of Non-throwing swap{Std::swap ( This-str, S.STR); }};
Of course, since there is always a cost to copy, the "very safe" situation is not possible in some cases.
C + + exception security and copy and swap policies