Re: What if new throws exeption?
On Dec 17, 5:58 am, "doublemaster...@gmail.com"
<doublemaster...@gmail.com> wrote:
somePtr *obj =NULL; ----------------------------(1)
obj = new somePtr; -----------------------------(2)
if(obj!=NULL) ------------------------------(3)
{
//do somthing
}
Is this code correct?
In what sense? It's certainly legal. If there's nothing between (2)
and (3), however, the if is guaranteed to be true.
first, "new" doesnt return NULL. I have read this some where. Or is
that (1) ensures obj NULL after (2) AFAIK, new throws exeption. So
will the (3) be exexuted?
More context is needed. There are definitely cases where something
like:
SomeType* obj = NULL;
try {
obj = new SomeType;
// ... do something with obj...
} catch (...) {
// do something else...
}
// obj is still in scope here...
delete obj;
but they aren't frequent. (At all, in fact. I'd qualify them as
rare.)
Reason i am asking this is, Its become a practise that checking for
NULL instead of trying for exeption. Is the above code really correct?
You don't check for null after new, and you don't "try for an
exception": you get an exception if there is not enough memory (unless
you've set the new_handler to do something else, like abort), and your
code should be able to deal with it.
One more question. If new fails, Do we need to call the destructor of
obj explicitly?? AFAIK objected isnt contructed so we donot need to
call destructor..am i right???
Obviously. The constructor can't be called until the memory is
allocated. If allocation fails, the constructor is never called.
--
James Kanze