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?
This is fixed with P2564R3 being accepted as a defect report for C++20. It allows
getVec()to be a subexpression of a larger constant expression without being a constant expression by itself.LLVM 17 and the upcomming GCC 14 implement it. For MSVC there is a feature request.
The original reason for the problem was this:
[expr.prim.id]p3:
[expr.const]p13:
static_assert( getVec().size() == 9 );is not in an immediate function context. Therefore, the explicit invocationgetVec()is an immediate invocation, so it needs to produce a constant expression.getVec()by itself is not a constant expression since it doesn't deallocate the memory allocated by new.For comparison, the following do compile https://godbolt.org/z/9KqhY7oP8