I played around with Godbolt\'s CompilerExplorer. I wanted to see how good certain optimizations are. My minimum working example is:
#include
int
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