Re: Exceptions & Constructors
* Erik Wikstr?m:
On 2007-07-30 13:15, jalqadir@gmail.com wrote:
The constructor in MyClass instantiates many objects pointers through
'new', I would like to implement a way to make sure that the object
has been allocated in memory by catch(ing) the bad_alloc exception
error, but this means that I have to throw this error back from
MyClass constructor, how can I avoid this?
Sure, add a flag to the class that tells if the object was constructed
correctly:
class Foo {
int* ptrarr[16];
public:
bool correct;
Foo() correct(true) {
try {
for (size_t i = 0; i < 16; ++i)
ptrarr[i] = new int();
} catch(bad_alloc&) {
correct = false;
}
}
};
int main() {
Foo f;
if (f.correct == false) {
// Opps, failed to allocate
}
}
Ouch, this is /very/ bad.
There's only one reasonable way to deal with memory depletion on a
modern system (until we get better operating systems), and that's to
install a terminating new handler.
Otherwise the program will continue to trash and will continue to fail,
and it's virtually guaranteed that some part of the code isn't able to
handle that.
And there's only one reasonable way to deal with construction failure,
and that is to throw an exception.
Otherwise you have zombie objects, requiring checking all over the place
and generally creating bugs & complexity, and that's what you have here.
You might want to consult Bjarne's article on exception safety in the
standard library. Available on net and as appendix to TCPPPL 3rd ed.
The memory leak in the code above is, in comparision, barely worth
mentioning, bad yes, but not a catastrophe like each of the two earlier
points.
Cheers,
- 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?