ARTICLE AD BOX
I have the following C++ code:
#include <vector> #include <array> constexpr int f() { std::vector<int> v; v.push_back(42); return v[0]; } int main() { constexpr int x = f(); return x; }This code compiles on recent versions of GCC and Clang with C++20 enabled. However, when inspecting the generated binary or running under a profiler, I still see heap allocation occurring at runtime.
How is this possible if f() is evaluated in a constant expression context? Is the compiler allowed to both constant-evaluate the expression and still emit runtime allocation code? What guarantees does the standard actually make about the absence of side effects or runtime work for constexpr evaluation?
I’m trying to understand where the boundary is between being evaluated at compile time and still generating runtime machinery, and how to think about this reliably when writing performance-critical code.
