Home >Backend Development >C++ >Can Compilers Optimize Away `new` Calls in C ?

Can Compilers Optimize Away `new` Calls in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 00:19:15703browse

Can Compilers Optimize Away `new` Calls in C  ?

Can the Compiler Eliminate Heap Memory Allocations?

In C , the new operator is used to allocate memory on the heap. Compilers may optimize code, including removing unnecessary statements. Can compilers eliminate heap memory allocations made using new?

Compiler Behavior

Research indicates that different compilers handle heap allocations differently:

  • g (5.2.0) and Visual Studio 2015 do not optimize out the new call.
  • clang (3.0 ) optimizes out the new call, even with full optimization flags.

Validity of Optimization

The validity of compiler optimizations is a subject of debate. Some argue that the compiler is not allowed to optimize out new calls as they may have observable behavior (e.g., throwing an exception). Others contend that optimizing out new calls is permitted if the compiler can guarantee that no observable behavior will be affected.

C 14 Standard

N3664: Clarifying Memory Allocation clarified the rules regarding compiler optimizations and memory allocation. It allows compilers to optimize around memory allocations in certain scenarios. However, the provision has been criticized as it potentially violates causality.

Additional Considerations

  • Non-throwing new: Clang also optimizes out calls to the non-throwing new operator.
  • Overridden operator new: Custom global operator new implementations in different translation units could affect the validity of compiler optimizations related to heap allocations.

Conclusion

The compiler's ability to optimize out heap memory allocations is a complex issue involving compiler behavior, language standards, and potential exceptions. While some compilers implement this optimization based on N3664, its validity remains a subject of discussion and depends on specific circumstances, including the C standard and the presence of custom memory allocators.

The above is the detailed content of Can Compilers Optimize Away `new` Calls in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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