Exception-safety of erase
From the C++ Standard (point 17.4.4.8 Restrictions on exception
handling [lib.res.on.exception.handling] $3) we now that every C++
Standard Library function which does not have any exception-
specification and is not described otherwise may throw anything
(including objects of types not derived from std::exception). Or am I
mistaken?
From the C++ Standard (point 23.1 Container requirements
[lib.container.requirements] $10) we now that ?erase? on a container
will never throw an exception. Copy constructor or assignment operator
of an iterator returned from a container does not throw any exceptions
as well.
But ?erase? specification (23.1.1 Sequences [lib.sequence.reqmts])
does not require it to take as an argument iterator returned by the
container. Actually it might take an argument of any type as long as
for ?q? being a valid dereferencable iterator into the container
expression ?erase(q)? is valid. But if it takes argument of a
different type then the iterator there is no guarantee in the Standard
that the conversion to that type will not throw.
Thous actually calling ?erase? might result in an exception although
in that case the execution will never get into erase. But that is of
little importance when we consider following code:
std::list< int > container;
const list< int >::iterator it = container.insert( container.end(),
0 );
try
{
/* do some actions which might end with an exception being thrown
*/
}
catch ( ... )
{
// Erase the inserted element to leave container without changes
in case of failure.
container.erase( it );
throw;
}
If my understanding of the C++ Standard (the above analysis) is
correct then this code is not actually exception-safe in the desired
manner. All because ?container.erase( it )? might throw an exception
during passing ?it? to ?erase? and thous not only the inserted element
will never be removed but a different exception will be thrown then
the one which caused entering to that catch.
Is this all correct?
If yes then there is virtually no way to have (portable) exception-
safe containers otherwise then by writing them from scratch on your
own.
If not then where am I mistaken? What part of Standard clarifies this?
Adam Badura
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]