I'm reading Scott Meyerses C++
and now I'm at the destructor throwing exceptions section. Here is what is he said:
When the vector
v
is destroyed, it is responsible for destroying all theWidget
s it contains. Supposev
has tenWidget
s in it, and during destruction of the first one, an exception is thrown. The other nineWidget
s still have to be destroyed (otherwise any resources they hold would be leaked), so v should invoke their destructors. But suppose that during those calls, a second Widget destructor throws an exception. Now there are two simultaneously active exceptions
So, as far as I undesrstood it, if the first element of a vector throws an exception it doesn't mean the program to be terminated right after that. The implementation tries to destroy the other objects in the vector instead. Let me provide an example:
#include<iostream>
#include<vector>
struct A
{
~A(){ std::cout << "destruction" << std::endl; throw std::exception(); }
};
int main()
{
A a[] = {A(), A(), A(), A(), A(), A()};
std::vector<A> v;
v.assign(a, a+6);
}
The program was terminated right after the first exception throwing. Where is the promised the second exception throwing?
terminate
s before it can even begin to destroy the other objects. – user657267