Will New Ever Return NULL?
In C , the new operator is responsible for allocating memory for new objects. According to the C Standard, if new fails to allocate memory, it is expected to throw a std::bad_alloc exception. However, there have been rumors that certain compilers, such as Visual C 6 (VC6), deviate from this behavior.
VC6's Non-Compliance
The rumors are true. VC6, by default, did not adhere to the C Standard in this regard. When new failed to allocate memory, it returned 0 (or NULL) instead of throwing an exception.
Microsoft's Workaround
Microsoft recognized this issue and provided a suggested workaround: using a custom new handler. Developers could specify their own implementation of operator new that would throw a std::bad_alloc exception instead of returning 0.
Later MSVC Compilers
In subsequent versions of MSVC (from 7.0 and later), the behavior of new became more complex. There was a set of rules that determined whether it would throw an exception or return 0.
VS2005 and Beyond
With VS2005 (MSVC 8.0), Microsoft finally cleaned up this behavior. By default, new now throws a std::bad_alloc exception unless explicitly linked to nothrownew.obj.
Alternative Approach: std::nothrow
Developers can also specify that they want new to return 0 instead of throwing an exception by using the std::nothrow parameter. This allows for a consistent behavior across compilers, even with legacy code that was written for VC6.
The above is the detailed content of What is the Behavior of the `new` Operator in Different C Compilers, Especially Regarding Memory Allocation Failure?. For more information, please follow other related articles on the PHP Chinese website!