Re: Question about exception safety
"Joshua Maurice" <joshuamaurice@gmail.com> schrieb im Newsbeitrag
news:63d76e7a-6225-4b2e-ab48-f700975a6778@f31g2000pri.googlegroups.com...
I'd like some input on this statement that I'm about to make.
It seems like complete overkill in this contrived example to worry
about the strong guarantee in light of out of memory errors. Unless
you've carefully analyzed your program for a particular implementation
and proved that there is sufficient memory (ridiculously hard for big
programs), then the out of memory error is just a fact of life, and as
demonstrated by this example, attempting to everywhere give the strong
guarantee is just silly.
One way to ensure that there will be enough memory might be to allocate a
huge block of memory during the initialization phase of the program and then
implement your own versions of operator new() and operator delete() that
take chunks from that block. The problem with that solution is that this
behaviour would be "unfair" towards other programs running on the same
system if you need only a fraction of the block you have usurped. Also, you
might still run out of memory and need to allocate another huge block, if
you can...
I would like to suggest to the OP that he identify the important
portions of his program which needs to be "atomic", such as the output
and persisted state of your program, and then focus his efforts there.
Don't worry too much about providing the strong exception guarantee on
each function as it's not normally needed, is wasteful, and results in
less clear code as the OP example shows. Again, instead refactor the
code to allow small commit or rollback checkpoints on the relevant
data and state which needs to be atomic.
Exception safe code is not necessarily less clear or wasteful. In my
original post, the first version of the function looks like this:
String f()
{
String result;
result = "some value";
cout << "some output";
return result;
}
And the final version looks like this:
auto_ptr<String> f()
{
auto_ptr<String> result = new String;
*result = "some value";
cout << "some output";
return result;
}
The only differences are the dynamic memory allocation, the use of a
std::auto_ptr and the need to dereference "result". (By the way, the first
line in the second version of the function should not compile. It does on
Microsoft Visual C++ 2005 Express Edition, leading to undefined behaviour,
for further information see:
http://stackoverflow.com/questions/270347/replacing-auto-ptr-in-vc-8)
--
Matthias Hofmann
Anvil-Soft, CEO
http://www.anvil-soft.com - The Creators of Toilet Tycoon
http://www.anvil-soft.de - Die Macher des Klomanagers
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]