However, I hardly see this version in my experience.
You would use it (or, equivalently, catch the exception from the default version) if you can handle the failure locally; perhaps by requesting to free some other memory and then retrying, or by trying to allocate something smaller, or using an alternative algorithm that doesn’t need extra memory.
Is there any reason that we prefer the default one against the nothrow one?
The general principle of exceptions: if you can’t handle it locally, then there’s no point in checking locally. Unlike return values, exceptions can’t be ignored, so there’s no possibility of ploughing on regardless and using a null pointer.
Even in a project that is not using exception?
Often, an out-of-memory condition can’t be handled at all. In that case, terminating the program is probably the best response; and that is the default response to an unhandled exception. So, even if you’re not using exceptions, the default new
is probably the best option in most situations.
should I check return value of
malloc()
?
Yes: that’s the only way to check whether it succeeded. If you don’t, then you could end up using a null pointer, giving undefined behaviour: often a crash, but perhaps data corruption or other bizarre behaviour and long debugging sessions to (hopefully) figure out what went wrong.
Why we treat
malloc()
andnew
differently in this case?
Because malloc
forces us to check the return value, while new
gives us the option of less intrusive error handling.