I was wondering about this recently. How is evaluation of constexpr function calls at compile time implemented by compilers such as gcc?
The most convenient way seems to use the function's compiled machine code or more likely some compiled intermediate code and execute it, but this has some problems. In the 2020 standard dynamic allocation was allowed in constexpr functions. What if a constexpr function has some incorrectly written memory management code and say, tries to double-free a pointer? It'd be better if the compiler didn't crash in such a case. What if it smashes the stack and overwrites data elsewhere in the compiler process? Similarly, it'd be better if the compiler didn't crash. Does the compiler execute it in a sandbox environment? How does it detect such memory errors? What does it do if such memory errors happen? Does the compiler instead emulate the function some other way? Thank you.
Basically they evaluate constexpr by using a special constexpr interpreter.
Here you can read/watch about clangs implementation
It's too much for a simple answer...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With