if (int* rc = new(std::nothrow) int[size]) {
return rc;
} else {
cout << "New failed, unable to allocate" << object_name <<
", size needed:" << sizeof( int ) * size << "." << endl;
exit..., return... whatever, just don't use rc.
}
A lot of the comments (here and elsewhere) are about "why bother to handle?" Your program can't work, new/alloc errors don't happen on today's big (virtual) machines, etc.
Think about how a program with an undetected 'new' error (or any error, for that matter) fails. For 'new', sometime later, you usually see an access violation. It may, or may not, be associated to the original failing statement/variable(s).
Now, pretend you are a user running this program (that, probably, you did not write). I usually see: "Access violation... core dumped" (or similar)?
I want to see: "New failed, unable to allocate 'fluff', size = 24GB. Program terminated."
In the first example, the user calls the developer (at 2am, because these are always critical errors at worst possible time), and a major debugging effort ensues. Time to solve: hours? Days?
In the second case, the user says "24GB? What the heck? Check the input - oh, oops, typo, I meant to say 24KB. Let me fix that." Time to solve: minutes. No call, no frustration.
Good diagnostics that the user can understand prevent [emergency] phone calls! Note, for example, even though I am allocating 'int's, that I included the logical object name, which hopefully means something to the user, and will aid him in fixing his problem. (Ummm, in case it need be said, emit the diagnostic at whatever level appropriate, just produce it and make it useful; it IS worth the effort.)