Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!mcsun!ukc!axion!ist!andrew From: andrew@ist.CO.UK (Andrew Grant) Newsgroups: comp.lang.c++ Subject: Re: Failed allocation in constructors? Message-ID: <2809@istop.ist.CO.UK> Date: 17 Jul 90 12:33:14 GMT References: <860@grenada.UUCP> Organization: Imperial Software Technology, London, UK Lines: 58 From article <860@grenada.UUCP>, by roger@grenada.UUCP (Roger Corman): > In article <9075@goofy.Apple.COM> escher@Apple.COM (Michael Crawford) writes: >>Can anyone suggest strategies for handling failed memory allocation >>in constructors? >> > This is the problem that has been most bothering me about C++. > > How then do we test for constructor failure? > > C++ provides a way of intercepting failed calls to new(), via the > 'new() handler'. This allows deallocation of unnecessary storage and other > measures to be taken when memory allocation fails. This is a very > useful language feature, but doesn't really solve my problems. It > isn't useful for automatic object allocation (on the stack) because > new() isn't called. True, new() is called by my constructor to allocate > other space for object-related things, but the problem is not at this > level. My problem is how to handle the case when the object cannot > be allocated (for whatever reason). The constructor needs to be able > to notify the routine which invoked it. The other problem with the > new handler is that it is not customizable on a per class basis (I > can't have a different one for each class). > If space for the object cannot be allocated, the constructor will not be called (see final paragraph of page 235 of Lippmans C++ Primer, if you don't have it I recomend buying it). In the case of stack allocation, stack overflow handling is normally implementation dependent. If the constructor allocates additional memory it will of course have to handle any problems with alloacting sufficent space. The usual options are program termination, freeing up of some other memory, or setting some kind of flag inside the class that member functions can test. . . . . . . . . . . . . . . . . . . . . . . . . . . .