I came across this term exception safe of containers. I want to understand what exactly exception safe mean? Are there are any comparison for this for different containers ?
-
https://en.wikipedia.org/wiki/Exception_safety – Sebastian Redl Feb 05 '16 at 09:06
-
1There are many resources talking about exception safety. Typically we talk about [*levels* of safety](https://en.wikipedia.org/wiki/Exception_safety). High-profile experts like [Herb Sutter](http://www.gotw.ca/gotw/059.htm) have written about how to achieve this. – BoBTFish Feb 05 '16 at 09:06
-
I understand exception safety now and its three canonical forms. But what does exception safety for a container mean ? Does it mean to even containers can throw exceptions ? – Barry Feb 05 '16 at 09:16
-
This is pretty good: http://www.boost.org/community/exception_safety.html – juanchopanza Feb 05 '16 at 09:27
-
effective c++/stl by scott meyers is the book to start off with....almost all containers provide some guranteed exception safety as per c++ spec. – basav Feb 05 '16 at 11:17
1 Answers
If you look at the algorithms for various data structures, you can see that they involve a sequence of steps. The data structure has some integrity (consistent internal meaning) at the beginning of the steps and at the end.
For example, consider vector
, which involves a dynamically growing array. This usually involves an array, an integer describing the size of the array, and an integer describing the number of used elements. When an element is inserted, a new array of twice the size might be allocated, elements copied to the new one, the integer describing the size will be multiplied by two, the integer describing the number of used elements will be increased by 1, etc.
An exception thrown at this point (e.g., by the copy constructor of the elements), can lead to the sequence of steps to be terminated in the middle. E.g., if you carelessly first update the integers, only then do the allocation and copies (and don't catch exceptions), then the data structure will lose its internal consistency.
The meaning of exception safety for STL containers, is that they have guarantees that such terminations will leave the data structure in a consistent state.

- 74,578
- 11
- 141
- 185
-
-
Yes. Basically, they each guarantee some form of exception safety. You should design your classes to be well behaved (e.g., not `throw` in destructors), and can improve things by also supporting move semantics. Consult the individual container documentation for its guarantees. – Ami Tavory Feb 05 '16 at 11:14
-
effective c++ by scott meyers is the book to start off with....almost all containers provide some guranteed exception safety as per c++ spec. – basav Feb 05 '16 at 11:14