Home > Article > Backend Development > Does `new` Always Throw `std::bad_alloc` in C ?
True Exceptions: Beyond the Norm in C Memory Management
Contrary to the C standard, it has been reported that some compilers, such as VC6, deviate from the expected behavior of returning std::bad_alloc exceptions when new fails to allocate memory.
Typically, when new fails to acquire the requested memory, it triggers an std::bad_alloc exception, adhering to established C standards. However, in the case of VC6, an alternative approach was taken.
Instead of returning an exception, VC6 reportedly returned 0 (or NULL) upon memory allocation failure. This behavior, which differs from the standard, could lead to confusion and unexpected results in code.
To combat the issue, Microsoft introduced a custom new handler as a recommended solution. However, in Visual C 7.0 and 7.1 (VS2002 and VS2003), a complex set of rules determined whether new would behave in a non-throwing or throwing manner.
With the release of Visual C 8.0 (VS2005), Microsoft resolved the matter by enforcing a consistent policy. In this version, new would always default to throwing an exception, unless explicitly linked with the nothrownew.obj object file.
For developers working with older code designed for VC6, the std::nothrow parameter can be utilized to mimic the behavior of new in that compiler. By specifying new(std::nothrow), the code can be mechanically altered to function similarly across different compilers, eliminating the need to overhaul existing error handling mechanisms.
The above is the detailed content of Does `new` Always Throw `std::bad_alloc` in C ?. For more information, please follow other related articles on the PHP Chinese website!