Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ucsd!usc!apple!escher From: escher@Apple.COM (Michael Crawford) Newsgroups: comp.lang.c++,apple.general Subject: Failed allocation in constructors? Keywords: exception handling Message-ID: <9075@goofy.Apple.COM> Date: 10 Jul 90 23:07:39 GMT Organization: Apple Computer Inc., Cupertino, CA Lines: 78 Can anyone suggest strategies for handling failed memory allocation in constructors? Constructors may not have return values, and aren't even void. I have seen some references to how there is not unified method, and one just needs to hack it. Example source code I have seen does not even address the issue, and just assumes the construction succeeds. The problem, as I see it, is that what one does upon memory failure depends greatly on the situation: do you crash and burn, wait, advise the user to close documents, or free a sentinel block (a large block allocated at the start of a program to provide a reserve) and retry the allocation? Here is a the problem: class foo { char *thePtr; public: CauseACrash(); foo(); ~foo(); } void theFun() { foo theFoo; // foo(), the constructor, gets called foo.CauseACrash(); // ~foo() gets called here, if we're still running! } foo::foo() { thePtr = NewPtr( 123456789 ); if ( thePtr == (char*)NULL ){ // Whadda I do? } } foo::CauseACrash() { int i; for ( i = 0; i < 123456789; i++ ){ *i = 'Q'; } } On a Mac, CauseACrash will scrawl all over the interrupt vector table; on Unix, it should core dump (if page 0 is mapped out, as good Unices do). Seems to me a member function ought to be able to assume that its instance is valid, and one should not have to validate every instance one creates; the fact that the object is dynamically allocated should be hidden to the user. This would mean that the failure should be handled within the constructor. I can conceive of some ways to do it, but I am a beginner here, and having enough trouble figuring out the language. Others must have invented this wheel before, care to roll one by me? I will summarize and post if you mail me suggestions, though this looks like a general enough problem to have an open discussion. Thank you very much, -- Michael D. Crawford Oddball Enterprises Consulting for Apple Computer Inc. 606 Modesto Avenue escher@apple.com Santa Cruz, CA 95060 Applelink: escher@apple.com@INTERNET# oddball!mike@ucscc.ucsc.edu The opinions expressed here are solely my own. alias make '/bin/make & rn'