In C , the new operator is commonly used to allocate memory on the heap. However, the question arises whether the compiler is permitted to optimize out these heap memory allocations.
According to N3664: Clarifying Memory Allocation, the compiler is allowed to optimize around memory allocations. This optimization is based on the "as-if" rule, which states that implementations can disregard requirements as long as the result appears as if the requirements were met. Since new can throw an exception, some argue that it cannot be optimized out due to its observable behavior.
However, proponents of optimization contend that the "as-if" rule applies even in this case. They argue that the compiler can determine that the allocation will not cause an exception and that eliding the new call would not violate the rule. Additionally, it is argued that the compiler can prove that no replacement global operator new would affect observable behavior, allowing it to perform the optimization.
While most compilers do not optimize out new calls, some exceptions exist. Clang, for example, has implemented the optimization that later became part of C 14. However, in cases where a non-throwing version of new is used or where a replacement operator new is possible, the optimization may not be performed.
The compiler's ability to optimize out heap memory allocations is a complex issue with varying interpretations of the "as-if" rule. While some implementations allow such optimization under certain conditions, others strictly follow the standard and do not perform it.
The above is the detailed content of Can C Compilers Optimize Out Heap Memory Allocations Using `new`?. For more information, please follow other related articles on the PHP Chinese website!