Re: Exception safety: how to assign std::string when strong guarantee is needed?
* Niels Dekker - no return address:
How would you assign one std::string to another, when you need to have
the "strong guarantee", with respect to exception safety?
It seems to me that the following five attempts only offer the basic
guarantee:
void Foo( const std::string & string1, std::string & string2 ) {
// Attempt 1. operator=
string2 = string1;
// Attempt 2. Copy-and-swap.
std::string(string1).swap(string2);
// Attempt 3. Copy-and-swap (non-member).
std::string temp(string1);
swap(string2, temp);
// Attempt 4. assign.
string2.assign(string1);
// Attempt 5. assign iterator-range.
string2.assign(string1.begin(), string1.end());
}
Your help is appreciated!
This one's very easy. You install your own new-handler, which calls
std::terminate. Then out-of-memory condition won't cause an exception,
and so you're guaranteed that there's no exception from that.
Otherwise, any attempt to allocate memory may cause an exception.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]