Mail Archives: djgpp/1999/06/03/18:43:34
Chris Mears wrote:
>
> Hi all...
>
> What does new return if it fails? I've heard that the standard requires
> that it throw an exception, but also I've heard that it returns NULL
> (like malloc). I did a test, and it did neither, preferring to exit the
> program. So, how do I capture this and use it for the greater good
> (rather than just exiting the program)?
>
> Chris
Looking at a draft version of the C++ spec and Stroustrup I think the
answer is "depends". The single parameter version of new, size_t, will
throw an exception bad_alloc if allocation fails. Other nothrow versions
return 0 if allocation fails. An example from Stroustrup:
void f()
{
int*p = new int[100000}; //may throw bad_alloc
if(int*q = new(nothrow) int[100000]);
{ //will not throw exception
}
else {
// allocation failed
}
}
Ralph
- Raw text -