C 20 constexpr Vector and String Not Working
In this issue, a programmer attempts to create constexpr objects of std::string and std::vector, but encounters a compiler error stating that the expression must have a constant value. The issue arises despite using the latest Microsoft Visual Studio 2019 version, which supports constexpr strings and vectors.
Problem Explanation
The error stems from the limited constexpr allocation support in C 20, which only allows for transient allocation. Transient allocation requires the allocated memory to be completely deallocated by the end of constant evaluation.
Example of Invalid Code
The following example illustrates the error:
int main() { constexpr std::vector<int> v = {1, 2, 3}; }
Here, the allocation for v persists, making it non-transient. The compiler correctly produces an error indicating that the expression did not evaluate to a constant because v holds onto a heap allocation during constant evaluation.
Example of Valid Code
However, using std::vector during constexpr time is possible with transient allocation.
constexpr int f() { std::vector<int> v = {1, 2, 3}; return v.size(); } static_assert(f() == 3);
In this example, v's allocation is transient since the memory is deallocated when f() returns. This allows for the use of std::vector during constexpr time.
The above is the detailed content of Why Aren't My C 20 `constexpr` `std::vector` and `std::string` Working?. For more information, please follow other related articles on the PHP Chinese website!