Since C++20 we can allocate memory during compile time and we have to free that during compile time. Therefore this raised some questions for me: first why does this work?
constexpr int* return_ptr() {
return new int{ 1 };
}
void call_return_ptr(){
int* int_ptr = return_ptr();
}
int main() {
call_return_ptr();
return 0;
}
I'm using the ptr returned from constexpr and not freeing that during compile time. This should be an error based on what I've understood.
Secondly if the first example works then why this shouldn't work:
constexpr int* return_ptr() {
return new int{ 1 };
}
void call_return_ptr(){
constexpr int* int_ptr = return_ptr();
}
int main() {
call_return_ptr();
return 0;
}
and even if we try to delete the pointer during compile time like this:
constexpr int* return_ptr() {
return new int{ 1 };
}
constexpr void call_return_ptr(){
constexpr int* int_ptr = return_ptr();
delete int_ptr;
}
int main() {
call_return_ptr();
return 0;
}
this is still an error. What is going on here?
---EDIT
Nicol Bolas gave a very good and profound answer to first and somewhat second part of my question, but that still leaves why the third version (the one that call_return_ptr is also constexpr) isn't working. Based what's on the comments on Nicol Bolas's answer, it is still unclear to me, why even if we change the third version's function signature to consteval that still gives an error since everything in call_return_ptr should be in a constexpr context.
constexprfunctions can be called both a compile-time and run-time, so the fact that the first example works doesn't imply that the second should.