According to C++ reference, you can new an object by:
MyClass * p1 = new MyClass;
or by
MyClass * p2 = new (std::nothrow) MyClass;
The second one will return a null pointer instead of throwing an exception.
However, I hardly see this version in my experience.
For example Google does not recommend using exception in their code, but they are not using the nothrow version either in Chromium as I can see.
Is there any reason that we prefer the default one against the nothrow one? Even in a project that is not using exception?
-- EDIT --
Follow up question: should I check return value of malloc()
?
It looks like, on the contrary, many people advice to check return value of malloc, some said because:
many allocation failures have nothing to do with being out of memory. Fragmentation can cause an allocation to fail because there's not enough contiguous space available even though there's plenty of memory free.
Is this true? Why we treat malloc()
and new()
differently in this case?