nothrow new: the Variant to Use When Avoiding C++ Exceptions

I'm a relatively young C++ developer, having spent the majority of my career programming in C. While I've devoted myself to the study of the language, I still frequently learn about new features and capabilities that surprise me.

I recently learned about nothrow new, a version of the new operator which returns a nullptr on failure instead of throwing an exception. While I have never seen this new operator usage in the wild, it's a valuable addition to my toolkit, as I often write embedded C++ programs without exceptions enabled.

In order to use the std::nothrow variants of new, you need to include the <new> header. Then you can overload new with std::nothrow:

int32_t* buffer = new (std::nothrow) int[100000000ul]; //non-throwing overload

If your system cannot allocate the memory, new will return nullptr rather than throwing std::bad_alloc.

Further Reading