Home > Backend Development > C++ > body text

Does Your C Compiler Correctly Handle `new` Operator Exceptions?

Linda Hamilton
Release: 2024-11-19 05:33:02
Original
795 people have browsed it

Does Your C   Compiler Correctly Handle `new` Operator Exceptions?

New Throwing Exceptions: An Examination of C Standard Compliance

The C standard mandates that the new operator throw a std::bad_alloc exception if memory allocation fails. However, concerns have been raised about the behavior of certain compilers, particularly VC6, in this regard.

VC6: Breaking the Standard

Confirming the rumors, VC6 exhibits non-compliant behavior. Instead of throwing an exception when encountering an allocation failure, it returns a 0 (or NULL) value. This deviation from the standard poses a potential challenge for developers as it requires explicit null checks after each new call, resulting in code aesthetics issues.

A Custom Workaround for VC6

To mitigate this issue in VC6, Microsoft provides a workaround involving a custom new handler. This solution supplements the default behavior with exception handling.

Variable Behavior in Newer MSVC Compilers

In MSVC compilers from version 7.0 onwards, the behavior of new is more complex. These compilers may default to either throwing or non-throwing behavior based on specific rules, including the linkage to the nothrownew.obj object file.

Consistency in MSVC 8.0 and Beyond

With the release of MSVC 8.0 (VS2005), a more consistent approach was adopted. This compiler always defaults to throwing new exceptions unless explicitly linked to nothrownew.obj.

Using std::nothrow for Non-Throwing Behavior

Developers can explicitly request that new return 0 rather than throwing an exception by using the std::nothrow parameter. This allows for backward compatibility with existing code written for VC6 behavior.

By understanding these nuances and implementing appropriate workarounds, developers can ensure that their C code adheres to the standard, regardless of the compiler they use.

The above is the detailed content of Does Your C Compiler Correctly Handle `new` Operator Exceptions?. 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