Re: exception in string
* George:
I am reviewing the exception safety of some code and met with some issues
about exception safety in string, which I can not find the answer at hand.
<url:
http://www.google.com/search?q=exception+safety+in+the+standard+library>
First 2 hits.
I
think the 3 code segments may all throw exceptions.
They can.
Because the storage of
string internal character data is on heap (using allocator for char?), so
when there is low memory, there will be bad_alloc exception?
1. Initialization
[Code]
string str1 = "Hello"; // or string str ("Hello");
[/Code]
2. Assignment
[Code]
string str2 = str1; // str1 is another string object or reference.
[/Code]
3. Empty construction
[Code]
string str;
[/Code]
I am not quite sure about (3).
In a well-designed program none of these will ever throw any exception,
because you will have replaced ::operator new with one that in case of
memory depletion (1) possibly frees some preallocated chunk of memory to
make a little room, (2) logs the error and (3) terminates the program.
That's the only sane general way to handle memory depletion, because
when it happens you will normally not have the resources to continue
normal execution. std::bad_alloc is, as the name implies, very bad.
Cheers, & hth.,
- Alf
--
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?