 |
Wednesday, October 31, 2001 |
 |
|
new/delete and Disabled Exceptions
If you're building a C++ program with exceptions turned off, you still could be in a situation where an exception can be thrown. The default implementations of operator new will throw an exception when memory is exhausted.
There are two possible solutions. The first is to include the <new> header and use the std::nothrow variation of new and delete.
#include <new>
...
char *str = new (std::nothrow) char[50];
This is a special, standard form of placement new that does not throw an exception.
A second solution would be to provide your own override for new and delete. To do this, add the following lines to a header file included in all of your source files
#include <new>
inline void * operator new(unsigned long size)
{
if (size) return MemPtrNew(size);
return MemPtrNew(1);
}
inline void operator delete(void *ptr)
{
if (ptr) MemPtrFree(ptr);
}
inline void * operator new[](unsigned long size)
{
if (size) return MemPtrNew(size);
return MemPtrNew(1);
}
inline void operator delete[](void *ptr)
{
if (ptr) MemPtrFree(ptr);
}
This method has the advantage of working on non-global launches. The nothrow form still throws an exception, its just caught before it returns to user code. Exceptions require globals to work right. The disadvantage of this code is that standard C++ code that expects exceptions to be thrown when there is a problem allocating memory could malfunction.
Update (17 December 2002)
A letter from a user has required me to update this article a little. I've added inline forms of the array new and array delete. These are needed if you allocate an array of items. I've also added checks in my inline code for a zero size, since C++ requires that a zero-byte allocation be valid, but Palm OS's MemPtrNew will cause a fatal exception if that's passed to it.
|