scott@stl.stc.co.uk (Mike Scott) (08/03/90)
This is no doubt a common problem, but I can't find any way of dealing with it cleanly. If a constructor needs to allocate extra storage, and this secondary allocation fails, how best can the constructor inform its invoker of the failure? One is in the position of having memory allocated for the 'basic' member, which contains duff data. Logical design requires that the constructor clean up, delete itself, and inform the caller of the problem. There are quite a few applications that cannot simply stop if memory runs out. For example, class test { char *ptr; int len; public: test(const char *); // etc }; test::test(const char *s) { len = strlen(s); ptr = new char[len+1]; if( ptr!=0 ) // did we get some memory??? (void)strcpy(ptr,s); else { // well, what can one do here ? } } It would be nice to be able to return 0, which is what happens anyway if there is no memory for the member data structure, but there seems to be clean no mechanism for doing this. I don't really want to have to keep a global flag around to track memory allocation failures like this. Closely related question: Is it legal to do a "delete this" within a constructor: obviously as the last statement :-) Probably best to post replies directly to me, and I'll summarize if the solution is non-trivial. Thanks. -- Regards. Mike Scott STL, London Road, Harlow, Essex CM17 9NA, UK scott@stl.stc.co.uk <or> ...uunet!mcsun!ukc!stl!scott <or> PSI%234237100122::SCOTT phone +44-279-29531 xtn 3133.