Path: utzoo!attcan!uunet!seismo!dimacs.rutgers.edu!mips!apple!lsr From: lsr@Apple.COM (Larry Rosenstein) Newsgroups: comp.lang.c++,apple.general Subject: Re: Failed allocation in constructors? Keywords: exception handling Message-ID: <9094@goofy.Apple.COM> Date: 11 Jul 90 21:51:16 GMT References: <9075@goofy.Apple.COM> Organization: Apple Computer, Inc. Lines: 46 In article <9075@goofy.Apple.COM> escher@Apple.COM (Michael Crawford) writes: > >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 The purpose of the constructor is to put the object in a known, consistent state. This doesn't necessarily mean it is in a valid or normal state. Probably the best approach is to have the contructor flag the invalid object, and have the other methods check the validity before proceeding. After the client creates the object, it can check to see if the creation succeeded. If it doesn't check, then error can be reported later, but at least everything is consistent, and the client can handle the error as it chooses. I don't think a constructor should try to decide what to do about the error (e.g., crash, advise the user, etc.); that's the function of higher levels of software. Freeing a sentinel block is a common approach on the Macintosh, but this is normally done at a lower level (within a Memory Manager GrowZoneProc). Another approach would be similar to what is done in Object Pascal. The constructor is set up to do initialization that can't fail, and there is a separate initialization step that the client has to explicitly call, which can return an error. (This makes things more complicated for the client, of course.) The issue isn't just that constructors don't return a value. One can always use setjmp/longjmp to break out of the constructor. The problem is recovering, which requires that destructors be invoked for automatic objects, for example. (The proposed C++ exception handling mechanism does this, for example.) >On a Mac, CauseACrash will scrawl all over the interrupt vector table; on True, but not very useful. -- Larry Rosenstein, Object Specialist Apple Computer, Inc. 20525 Mariani Ave, MS 46-B Cupertino, CA 95014 AppleLink:Rosenstein1 domain:lsr@Apple.COM UUCP:{sun,voder,nsc,decwrl}!apple!lsr