C++:new
lastmod 2017-09-24created 2014-03-315 edits
Notes on the C++ new keyword.
Misconceptions about exception handling for the new operator
Not long ago, I found the following code in source someone had written. It allocated about 100MB of memory and then handled the exception in case the allocation failed.
At a glance this code looks completely fine, but in fact it has a very big problem. That's because even if the new operator fails, it will NEVER. EVER. enter the if block. If you saw this code and felt nothing odd at all... let's take a moment to reflect. ^^; (In fact, memory allocation by the new operator almost never fails, so code like the above often slips by unverified.)
According to the C++ standard, when memory allocation by the new operator fails, it throws an exception of type std::bad_alloc. So in the code above, if allocation fails, NULL is not returned to the ptr variable; instead an exception of type std::bad_alloc is thrown, and since this exception is not handled anywhere, the program terminates abnormally. Then how should exception handling for a failed new allocation be implemented properly?
Correct exception handling for the new operator 01: try-catch
Naturally, the first approach that comes to mind is handling the exception with a try-catch statement. Wrap the code using the new operator in a try block, and handle the std::bad_alloc exception in the catch clause.
char* ptr;
try {
ptr = new char[0x7ffffffe];
} catch (std::bad_alloc e) {
wcout << e.what() << endl;
}
Note that in an MFC environment, a CMemoryException exception is thrown instead of std::bad_alloc (operator new is overloaded), so you must implement it as below.
Correct exception handling for the new operator 02: new(std::nothrow)
This is for those who say, 'I just don't like the try-catch style of exception handling.' If you use new(std::nothrow) instead of new, it returns NULL instead of throwing an exception when memory allocation fails (this is also specified in the C++ standard). So when using new(std::nothrow), you can implement exception handling in a style similar to the incorrect code written at the top.
Dynamic memory managementLow level memory management
Favorite site
- cppreference.com - operator new
- CodeProject - How to use global new/delete after overloading it
- C++ Memory and Resource Management