Sunday, June 13, 2010

std::nothrow new

Sometime during the new operation it might fail the process due to certain reason, this isn’t a big deal because exception could be a good friend to help out. Unfortunately exception still have its own limitation where it might not able to find the matching catch() clause due to the mistake of programmer. Or it could be in other situation; CRT’s new will return a NULL pointer whereas standard C++ will throw a std::bad_alloc exception when memory allocation failed.

Instead of worrying:-
1. How does the programmer know about how the exception going to catch?
2. The programmer has to be aware that he/she is dealing with CRT’s version of new or standard version of new.

Let’s put in alternative point of view:
What if the programmer knows that the new operator is NOT going to throwing any exceptions?

Thus, std::nothrow new would be the best solution. This will guarantee that the new will only return either a NULL pointer or a valid pointer.

Here is the sample usage:
Foo *p;
p = new(std::nothrow) Foo();
if( !p ) { exit(1); }

1. msdn reference
2. C++ reference guide

No comments: