C++ – nothrow delete in C++

cmemory-managementvisual c++

This MSDN page mentions that there're nothrow versions of new and delete. nothrow new is quite a known thing – returns null instead of throwing an exception if memory allocation fails. But what is nothrow delete mentioned there?

Best Answer

They are probably referring to the raw memory allocation functions operator new and operator delete.

When you invoke a specific version of placement new-expression (i.e. new-expression with extra parameters; they all are officially referred to as placement forms of new) and the memory allocation function operator new succeeds, but the process fails later for some other reason (the constructor throws), the implementation has to abort the process and automatically release the allocated memory by calling the appropriate version of operator delete. "Appropriate version" of operator delete in this case is the version that has the same set of parameters as the operator new function previously used for memory allocation (except for the very first parameter, of course).

This applies to nothrow version of operator new as well. When you use a nothrow form of new-expression, it calls a nothrow version of operator new and then constructs the object in the allocated memory. If the constructor fails (throws), the implementation of the new-expression releases allocated memory with the help of nothrow version of operator delete. This is basically the only reason for this version of operator delete to exist.

In other words, the nothrow version of operator delete exists for very specific internal purposes. You should not normally want to call it yourself and, maybe, you don't really need to know about its existence. However, it is worth knowing that for the reasons described above, whenever you create your own version of operator new with extra parameters, it is always a good idea to provide a matching version of operator delete with the same set of extra parameters.