nothrow or exception ?

Posted by Muggen on Stack Overflow See other posts from Stack Overflow or by Muggen
Published on 2010-12-31T18:23:14Z Indexed on 2010/12/31 18:53 UTC
Read the original article Hit count: 139

I am a student and I have small knowledge on C++, which I try to expand. This is more of a philosophical question.. I am not trying to implement something.

Since

#include <new> 
//...
T * t = new (std::nothrow) T();
if(t)
{
    //...
}
//...

Will hide the Exception, and since dealing with Exceptions is heavier compared to a simple if(t), why isn't the normal new T() not considered less good practice, considering we will have to use try-catch() to check if a simple allocation succeeded (and if we don't, just watch the program die)??

What are the benefits (if any) of the normal new allocation compared to using a nothrow new? Exception's overhead in that case is insignificant ?

Also, Assume that an allocation fails (eg. no memory exists in the system). Is there anything the program can do in that situation, or just fail gracefully. There is no way to find free memory on the heap, when all is reserved, is there?

Incase an allocation fails, and an std::bad_alloc is thrown, how can we assume that since there is not enough memory to allocate an object (Eg. a new int), there will be enough memory to store an exception ??

Thanks for your time. I hope the question is in line with the rules.

© Stack Overflow or respective owner

Related posts about c++

Related posts about outofmemoryexception