Home > Backend Development > C++ > body text

Why Does `new` Sometimes Return NULL Instead of Throwing an Exception?

Linda Hamilton
Release: 2024-11-21 17:53:12
Original
829 people have browsed it

Why Does `new` Sometimes Return NULL Instead of Throwing an Exception?

New() Throwing a NULL Exception: Compiler Compliance

The C standard mandates that the new operator throws a std::bad_alloc exception when it fails to allocate memory. However, there have been concerns raised about the behavior of some compilers, particularly VC6, which may not adhere to this standard.

VC6's Non-Compliance

In the case of VC6, it has been confirmed that the new operator indeed did not follow the standard by default. Instead, it returned 0 (NULL) upon failure. This behavior posed challenges for developers because it required explicit checks for NULL after each new statement, making the code aesthetically unappealing.

Microsoft's Response and Workarounds

Microsoft acknowledged this non-compliance and provided a workaround using a custom new handler. Alternatively, developers could leverage the nothrownew.obj object file to mimic VC6's behavior in newer MSVC compilers (7.0 and later).

Current State of Compliance

Fortunately, in MSVC 8.0 (VS2005), the default behavior of new was amended to adhere to the standard and now throws a std::bad_alloc exception in case of memory allocation failure. Linkages to nothrownew.obj are necessary only if one desires the original VC6-like behavior.

Option for Manual Null Return

Developers have the flexibility to specify that new should return 0 instead of throwing an exception by utilizing the std::nothrow parameter:

SomeType *p = new(std::nothrow) SomeType;
Copy after login

This technique allows for a consistent approach across compilers and simplifies code maintenance by eliminating the need to modify existing error handling mechanisms.

The above is the detailed content of Why Does `new` Sometimes Return NULL Instead of Throwing an Exception?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template