Why isn't this unused variable optimised away?

后端 未结 4 1654
情深已故
情深已故 2021-02-06 21:47

I played around with Godbolt\'s CompilerExplorer. I wanted to see how good certain optimizations are. My minimum working example is:

#include 

int         


        
4条回答
  •  被撕碎了的回忆
    2021-02-06 22:30

    The compiler can't optimise heap-related code, as heap-related code is run-time specific. The heap-related code is the use of a std::vector, which holds the managed data in heap memory.

    In your example all values as well as the size is known at compile-time, therefore it's possible to use std::array instead, which is initialized by aggregate initialization, and therefore may be constexpr-qualified.

    Changing your example using std::array reduces your function to your expected output:

    #include 
    
    int foo() {
        std::array v {1, 2, 3, 4, 5};
        return v[4];
    }
    
    foo():                                # @foo()
            mov     eax, 5
            ret
    

    Using the given function will still result in a call to foo(). In order to eliminate the call, the function must be qualified as constexpr:

    #include 
    
    constexpr int foo() {
        constexpr std::array v {1, 2, 3, 4, 5};
        return v[4];
    }
    
    int main() {
        return foo();
    }
    
    main:                                   # @main
            mov     eax, 5
            ret
    

提交回复
热议问题