if new fails, the pointer would be 0 or NULL or false (thats the same, why i mention false, look at the bottom of my post)
if new successes, the pointer is an address, that means something that is NOT 0.
1 2 3 4 5 6
if (!newElem) ... means
if (!newElemn == true) thats the same as
if (newElem == !true) thats the same as
if (newElem == false) thats the same as
if (newElem == NULL) thats the same
if (newElem == 0)
so it checks if newElem is a NULL-pointer, that means "new" failed the line before.
remember: false = 0 and true is any other value
I don't think so, that new returns a NULL-pointer if he couldn't allocate memory. He would raise an exception named 'bad_alloc'. You can catch the exception.
In C you have to check if malloc fails, but not in C++. So this code is not valid C++.
What if there's no allocatable memory available? If the heap is entirely consumed? After all, the compiler doesn't know, since the allocation will occur at runtime. Where's new going to allocate from then?
The new keyword is designed to try and allocate memory. Although you kind of have to trust it to be able to, it's still not a significant cost to make SURE that it succeeded.
@MorningStar
im not very familiar with C++. needed a lot of C lately and now i just moved on to C++, so excuse me here if its not valid C++ code ;-)
i just checked my book im learning with and it uses try-catch with bad_alloc.
Good, now i know better. Thanks :-)
@WilliamY
look at what tummychow said.
and you should never rely on "it cant be possible here". murphys law: if it can go wrong, it will!
so be sure, that if it happens (even if its a chance of 1 in a million) your program can react and does not just close down.
but it still means the same as we said before: checking if the pointer is a NULL-pointer. if you dont understand my, kinda, confusing post before, sorry, but i dont know how to explain it in another way. (english is not my mother tongue and my english skills arent good enough to explain certain things)
I should add that my previous statement is true for val being of any basic type, including bool, integers, floating point types, and pointers. It doesn't apply for complex types (classes).