I'm writing a drop-replacement for a container, and I'm trying to
get all the exception-guarantees in place. I'm currently writing
the clear
method, and I want it to complete as much as possible,
and to always leave the container in a consistent state, even if
one of the destructors throw an exception. I also want to rethrow
the exception after I'm done cleaning, preferably without slicing.
This brings me to the question; when is an exception destructed? Lets have a look at one attempt: This is simplified for the example.
void container::clear()
{
bool had_exception = false;
std::exception* exp;
internal_set_empty(); // this cant throw
while( ! internal_done() )
{
try
{
internal_destruct_next(); // this might throw if T::~T() throws
}
catch( std::exception& e )
{
had_exception = true;
exp = &e;
}
}
if( had_exception )
throw *exp;
}
I expect this to fail badly, because the exception is probably destructed when it is considered handled, and this doesn't technically rethrow.
Another attempt would be taking a copy of the exception, something that I expect would slice.
Is there a way to extend the lifetime of the exception so I can rethrow
it later?
If possible, I would also like to be able to rethrow exceptions caught
via catch(...)
.