Since C++20, std::vector
can be used in constant expressions. And as far as I known, current C++ permits dynamically allocate memory under the condition that any such allocation is deallocated by the time the constant expression is "over".
However, I encounter that in case of immediate function the rules might be different. Please consider the example:
consteval auto getVec() {
return std::vector<int>(9);
}
static_assert( getVec().size() == 9 );
Here immediate consteval
function getVec
returns not-empty std::vector
, size of which is verified in a constant expression.
I expected that this code would compile, because all deallocations must be done automatically, and indeed it is accepted in Clang with libc++
.
But MSVC complains:
error C7595: 'getVec': call to immediate function is not a constant expression
note: (sub-)object points to memory which was heap allocated during constant evaluation
fatal error C1903: unable to recover from previous error(s); stopping compilation
and GCC behaves similarly:
error: 'getVec()()' is not a constant expression because it refers to a result of 'operator new'
Online demo: https://gcc.godbolt.org/z/d736qr3hh
Which compiler is correct here?
consteval
function inside a manifestly-constant evaluated expression is no longer by itself an immediate invocation, which seems to be what you expect of C++20. – Indignant