Exception safe of containers in c++

110 Views Asked by At

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 ?

1

There are 1 best solutions below

3
On

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.